来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subsets
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
题解:回溯法
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> results;
if (nums.size() == 0)
return results;
// 记录走过的路径
vector<int> subset;
subsetHelper(nums, 0, subset, results);
return results;
}
private:
void subsetHelper(vector<int>& nums, int startIndex, vector<int>& subset, vector<vector<int>>& results) {
results.push_back(subset);
for (int i = startIndex; i < nums.size(); i ++) {
// 做选择
subset.push_back(nums[i]);
// 回溯
subsetHelper(nums, i + 1, subset, results);
// 撤销选择
subset.pop_back();
}
}
};