78 Subsets
https://leetcode.com/problems/subsets/#/description
Given a set ofdistinctintegers,nums, return all possible subsets.
Note:The solution set must not contain duplicate subsets.
For example,
Ifnums=[1,2,3]
, a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
分析及代码
每次不想做题又要凑数就用这种backtracking打发hahah
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
for(int i = 0; i <= nums.length; i++) {
generate(nums, i, res, new ArrayList<>(), 0);
}
return res;
}
private void generate(int[] nums, int n, List<List<Integer>> res, List<Integer> item, int index) {
if(item.size() == n) {
res.add(new ArrayList<>(item));
return;
}
for(int i = index; i < nums.length; i++) {
item.add(nums[i]);
generate(nums, n, res, item, i + 1);
item.remove(item.size() - 1);
}
}