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) {
/* 和permutations 类似 全排列是当前长度达到数组长度记录一次答案 每次交换节点位置(for循环中)
* 本题采用tmp记录遍历路径上的父节点
*
* */
vector<vector<int>> ret;
vector<int> path;
dfs(nums, ret, path, 0);
return ret;
}
void dfs(vector<int> &nums, vector<vector<int>> &ret, vector<int> &path, int index){
ret.push_back(path);
for(int i=index;i<nums.size();i++){
path.push_back(nums[i]);
dfs(nums, ret, path, i+1);
path.pop_back(); // 恢复
}
}
};