一尘不染

数组的所有可能组合

algorithm

我有一个字符串数组

{"ted", "williams", "golden", "voice", "radio"}

并且我希望这些关键字的所有可能组合都采用以下形式:

{"ted",
 "williams",
 "golden", 
 "voice", 
 "radio",
 "ted williams", 
 "ted golden", 
 "ted voice", 
 "ted radio", 
 "williams golden",
 "williams voice", 
 "williams radio", 
 "golden voice", 
 "golden radio", 
 "voice radio",
 "ted williams golden", 
 "ted williams voice", 
 "ted williams radio", 
 .... }

我已经去了好几个小时了,没有得到有效的结果(高级编程的副作用?)。

我知道解决方案应该很明显,但是老实说,我被卡住了!接受Java / C#解决方案。

编辑

  1. 这不是功课
  2. “ ted williams”和“ williams ted”被认为是相同的,所以我只想“ ted williams”

编辑2 :查看答案中的链接后,事实证明番石榴用户可以在com.google.common.collect.Sets中使用powerset方法


阅读 557

收藏
2020-07-28

共1个答案

一尘不染

编辑: 正如FearUs指出的那样,更好的解决方案是使用Guava的Sets.powerset(Set
set)

编辑2: 更新的链接。


此解决方案的快速而肮脏的翻译:

public static void main(String[] args) {

    List<List<String>> powerSet = new LinkedList<List<String>>();

    for (int i = 1; i <= args.length; i++)
        powerSet.addAll(combination(Arrays.asList(args), i));

    System.out.println(powerSet);
}

public static <T> List<List<T>> combination(List<T> values, int size) {

    if (0 == size) {
        return Collections.singletonList(Collections.<T> emptyList());
    }

    if (values.isEmpty()) {
        return Collections.emptyList();
    }

    List<List<T>> combination = new LinkedList<List<T>>();

    T actual = values.iterator().next();

    List<T> subSet = new LinkedList<T>(values);
    subSet.remove(actual);

    List<List<T>> subSetCombination = combination(subSet, size - 1);

    for (List<T> set : subSetCombination) {
        List<T> newSet = new LinkedList<T>(set);
        newSet.add(0, actual);
        combination.add(newSet);
    }

    combination.addAll(combination(subSet, size));

    return combination;
}

测试:

$ java PowerSet ted williams golden
[[ted], [williams], [golden], [ted, williams], [ted, golden], [williams, golden], [ted, williams, golden]]
$
2020-07-28