给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
function backtrack(list, tempList, nums, start) {
list.push([...tempList]);
for (let i = start; i < nums.length; i++) {
tempList.push(nums[i]);
backtrack(list, tempList, nums, i + 1);
tempList.pop();
}
}
/**
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = function (nums) {
const list = [];
backtrack(list, [], nums, 0);
return list;
};
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
auto ret = vector<vector<int>>();
auto tmp = vector<int>();
backtrack(ret, tmp, nums, 0);
return ret;
}
void backtrack(vector<vector<int>>& list, vector<int>& tempList, vector<int>& nums, int start) {
list.push_back(tempList);
for (auto i = start; i < nums.size(); ++i) {
tempList.push_back(nums[i]);
backtrack(list, tempList, nums, i + 1);
tempList.pop_back();
}
}
};
class Solution {
// 结果
List<List<Integer>> res = new ArrayList();
public List<List<Integer>> subsets(int[] nums) {
backtrack(nums, 0, new ArrayList<Integer>());
return res;
}
public void backtrack(int[] nums, int start, ArrayList<Integer> track)
{
// 注意:深拷贝
res.add(new ArrayList(track));
for(int i=start; i<nums.length;i++)
{
// 做选择
track.add(nums[i]);
// 回溯
backtrack(nums, i+1, track);
// 撤销选择
track.remove(track.size()-1);
}
}
}
class Solution:
def subsets(self, nums):
self.res = []
self.track = []
self.backtrack(nums, 0, self.track)
return self.res
def backtrack(self, nums, start, track):
# 注意深拷贝
self.res.append(list(self.track))
for i in range(start, len(nums)):
# 做选择
self.track.append(nums[i])
# 回溯
self.backtrack(nums, i+1, self.track)
# 撤销选择
self.track.pop()