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.
Example 1:
Input: nums = [1,2,3] Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0] Output: [[],[0]]
Constraints:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
- All the numbers of
nums
are unique.
DFS.
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
def dfs(i, n, t):
res.append(t.copy())
if i == n:
return
for j in range(i, n):
t.append(nums[j])
dfs(j + 1, n, t)
t.pop()
dfs(0, len(nums), [])
return res
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
dfs(0, nums, new ArrayList<>(), res);
return res;
}
private void dfs(int i, int[] nums, List<Integer> t, List<List<Integer>> res) {
res.add(new ArrayList<>(t));
if (i == nums.length) {
return;
}
for (int j = i; j < nums.length; ++j) {
t.add(nums[j]);
dfs(j + 1, nums, t, res);
t.remove(t.size() - 1);
}
}
}
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
vector<int> t;
dfs(0, nums, t, res);
return res;
}
void dfs(int i, vector<int>& nums, vector<int> t, vector<vector<int>>& res) {
res.push_back(t);
if (i == nums.size()) return;
for (int j = i; j < nums.size(); ++j)
{
t.push_back(nums[j]);
dfs(j + 1, nums, t, res);
t.pop_back();
}
}
};
func subsets(nums []int) [][]int {
var res [][]int
var t []int
dfs(0, nums, t, &res)
return res
}
func dfs(i int, nums, t []int, res *[][]int) {
cp := make([]int, len(t))
copy(cp, t)
*res = append(*res, cp)
if i == len(nums) {
return
}
for j := i; j < len(nums); j++ {
t = append(t, nums[j])
dfs(j+1, nums, t, res)
t = t[:len(t)-1]
}
}