Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Solution:
求给出的集合的所有子集。
public static List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(nums == null || nums.length == 0) {
return res;
}
return findSubsets(nums, res);
}
public static List<List<Integer>> findSubsets(int[] nums, List<List<Integer>> res) {
int n = nums.length;
for(int i = 0; i < Math.pow(2,n); i++) { //一共有2的n次方种情况,那么结果就是从0到2的n次方-1
List<Integer> list = new ArrayList<Integer>();
String binary = Integer.toBinaryString(i);
for(int j = 0; j < n; j++) { //对于每一种情况,一共有n位需要查看,查看一趟得到一个结果存起来
int compare = 0; //默认当前位为0
if(j >= n-binary.length()) { //如果当前位有数字,那么将该位置的数字记在compare中
compare = Integer.valueOf(String.valueOf(binary.charAt(j-(n-binary.length()))));
} else {
compare = 0;
}
if(compare == 0) {
continue;
} else {
list.add(nums[j]);
}
}
res.add(list);
}
return res;
}