解法一:回溯法
java
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
backtrace(0, nums, result, temp);
return result;
}
public void backtrace(int i, int[] nums, List result, List temp){
result.add(new ArrayList<Integer>(temp)); // 加入元素个数为i的子集 这里类型强转要用new
for(int j=i; j<nums.length; j++){
// j=i表示j之前的元素遍历过了,要遍历j后面的元素
temp.add(nums[j]);
backtrace(j+1, nums, result, temp);
temp.remove(temp.size()-1);
}
// 1 2 3 的输出方式为[[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]]
}
}
注意:
- 这里类型转换要用new:
result.add(new ArrayList<Integer>(temp))
,而不是强转ArrayList<Integer>(temp)