一个数组的所有可能的组合 [英] 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.
修改
- 这不是一个功课
- 在特德·威廉斯和泰德·威廉姆斯被认为是相同的,所以我想特德·威廉斯只有
编辑2 :审查答案的链接后,事实证明,番石榴用户可以在com.google.common.collect.Sets的幂方法
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指出,一个更好的解决方案是使用番石榴的<一个href="http://docs.guava-libraries.google$c$c.com/git/javadoc/com/google/common/collect/Sets.html#powerSet(java.util.Set)"相对=nofollow> Sets.powerset(设置设置)。你可以看到code(约)<一href="https://$c$c.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/collect/Sets.java#1276"相对=nofollow>这里。
As FearUs pointed out, a better solution is to use Guava's Sets.powerset(Set set). You can see the code (around) here.
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屋!