题目来源:https://leetcode.cn/problems/subsets/description/
C++题解1:递归回溯法。由于是求子集,所以根据nums.size()遍历每个子集的长度,并进行回溯。
class Solution {
public:vector<vector<int>> res;vector<int> sub;void backtracking(vector<int> nums, int ind, int num) {if(sub.size() == num) {res.push_back(sub);return;}for(int i = ind; i < nums.size(); i++) {sub.push_back(nums[i]);backtracking(nums, i + 1, num);sub.pop_back();}}vector<vector<int>> subsets(vector<int>& nums) {int len = nums.size();for(int j = 0; j <= len; j++) {backtracking(nums, 0, j);}return res;}
};
C++题解2(来源代码随想录):不断地从自身开始收集子集,直到末尾。所以不用更新目标子集的长度。
class Solution {
private:vector<vector<int>> result;vector<int> path;void backtracking(vector<int>& nums, int startIndex) {result.push_back(path); // 收集子集,要放在终止添加的上面,否则会漏掉自己if (startIndex >= nums.size()) { // 终止条件可以不加return;}for (int i = startIndex; i < nums.size(); i++) {path.push_back(nums[i]);backtracking(nums, i + 1);path.pop_back();}}
public:vector<vector<int>> subsets(vector<int>& nums) {result.clear();path.clear();backtracking(nums, 0);return result;}
};