Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<int> temp;
vector<vector<int>> res;
backtrack(nums,res,temp,0);
return res;
}
void backtrack(vector<int> &nums,vector<vector<int>> &res,vector<int> &temp,int start){
res.push_back(temp);
for(int i=start;i<nums.size();i++){
temp.push_back(nums[i]);
backtrack(nums,res,temp,i+1);
temp.pop_back();
}
}
};
backtrack(nums,res,temp,i+1); i+1的含义是每次当遍历到比如[1,2,3]的3时,如果 backtrack(nums,res,temp,start+1);就会又遍历到3,变成[1,3,3], i+1保证每次遍历都是下一个开始