如何在Java中找到数组的所有子集? [英] How to find all the subsets of an array in java?
本文介绍了如何在Java中找到数组的所有子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用java查找数组的所有子集。如果我们有一组{1,2,3},那么我应该得到
{},{1},{2},{3},{1,2},{2,3},{1.3} ,{1,2,3}
I need to find all the subsets of an array using java.For e.g. if we have a set {1,2,3} then i should get {},{1},{2},{3},{1,2},{2,3},{1.3},{1,2,3}
推荐答案
您可以执行此操作,以避免需要递归求解。
You can do this to avoid needing to recurse the solutions.
public static <T> void printCombinations(T[] arr) {
for(long i = 0, max = 1L << arr.length; i < max; i++) {
Set<T> ts = new HashSet<>();
for(int j = 0; j < arr.length; j++) {
if ((i >> j) != 0)
ts.add(list.get(j));
}
System.out.println(ts);
}
}
这篇关于如何在Java中找到数组的所有子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文