78. Subsets

Given an integer array nums of unique elements, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

回溯,先添加一个空集,然后回溯各个单独节点。
递归时传入数组内当前数字之后的节点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
ret.add(new ArrayList<>());

for(int i = 0; i < nums.length ; i++){
backtrack(ret, new ArrayList<>(), nums, i);
}
return ret;
}

private void backtrack(List<List<Integer>> ret, List<Integer> arr, int[] nums, int i){
if(i == nums.length-1){
arr.add(nums[i]);
ret.add(new ArrayList<>(arr));
return;
}

arr.add(nums[i]);
ret.add(new ArrayList<>(arr));
for(int j = i+1; j < nums.length; j++){
backtrack(ret, arr, nums, j);
arr.remove(arr.size()-1);
}
}
}
Author

Xander

Posted on

2022-04-24

Updated on

2022-04-24

Licensed under

Comments