数组的所有可能组合 [英] All possible combinations of an array
问题描述
我有一个字符串数组
{"ted", "williams", "golden", "voice", "radio"}
并且我想要以下形式的这些关键字的所有可能组合:
and I want all possible combinations of these keywords in the following form:
{"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",
.... }
我已经使用了几个小时没有任何有效结果(高级编程的副作用??).
I've been going for hours with no effective result (side effect of high-level programming ??).
我知道解决方案应该是显而易见的,但老实说,我被卡住了!接受 Java/C# 中的解决方案.
I know the solution should be obvious but I'm stuck, honestly ! Solutions in Java/C# are accepted.
编辑:
- 这不是家庭作业
- ted williams"和williams ted"被认为是一样的,所以我只想要ted williams"
EDIT 2:查看答案中的链接后,发现 Guava 用户可以在 com.google.common.collect.Sets 中使用 powerset 方法
EDIT 2: after reviewing the link in the answer, it turns out that Guava users can have the powerset method in com.google.common.collect.Sets
推荐答案
正如 FearUs 指出的那样,更好的解决方案是使用 Guava 的 Sets.powerset(Set set).
As FearUs pointed out, a better solution is to use Guava's 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]]
$
这篇关于数组的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!