Description:
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 List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<Integer>());
for(final int num : nums) {
List<List<Integer>> newsub = new ArrayList<>();
for(List<Integer> cur : result)
newsub.add(new ArrayList<Integer>(cur){{add(num);}});
for(List<Integer> ls : newsub) {
result.add(ls);
}
}
return result;
}
解法二:
使用回搠法,backtrack。
每次向前探一步后往回走一步。
代码如下:
详细说明戳这里
public void backtrack(int first, ArrayList<Integer> cur, int[] nums) {
if(cur.size() == k)
result.add(new ArrayList<Integer>(cur));
for(int i = first; i < n; ++i) {
cur.add(nums[i]);
backtrack(i + 1, cur, nums);
cur.remove(cur.size() - 1);
}
}
public List<List<Integer>> subsets(int[] nums) {
n = nums.length;
for(k = 0; k < n + 1; ++k) {
backtrack(0, new ArrayList<Integer>(), nums);
}
return result;
}