题目
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
分析
回溯法
其实可以用多次组合法解决这个问题的。。
class Solution {
public static List<List<Integer>> subsets(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new LinkedList<>();
recursive(result, nums, list,0);
return result;
}
private static void recursive(List<List<Integer>> result, int[] num, List<Integer>list, int index) {
result.add(list);
for (int i = index; i<num.length; i++) {
List<Integer> newlist = new ArrayList<>(list);
newlist.add(num[i]);
recursive(result, num, newlist,i+1);
}
}
}