classSolution: defsubsets(self, nums: List[int]) -> List[List[int]]: defdfs(res, tmp, nums): res.append(tmp) for i in range(len(nums)): dfs(res, tmp+[nums[i]], nums[i+1:]) res = [] dfs(res, [], nums) return res
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> res; vector<int> tmp; sort(nums.begin(), nums.end()) backtrack(res, tmp, nums, 0); return res; } voidbacktrack(vector<vector<int>>& res, vector<int>& tmp, vector<int>& nums, int pos){ res.push_back(tmp); //add every set into the result for(int i = pos; i < nums.size(); i++){ tmp.push_back(nums[i]); //sequentially add every element in the result backtrack(res, tmp, nums, i+1); tmp.pop_back(); } } };