LeetCode 78 subset HERODING's LeetCode road

Given a set of integer arrays nums without repeated elements, return all possible subsets (power sets) of the array.

Note: The solution set cannot contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2 ],
[]
]

Problem-solving idea: It is
also a backtracking problem. First, arrange the array, and then put it into dfs to traverse. For each number, you can choose or not. If you don’t choose to skip directly, choose to put it in res and Continue down, remember to have a backtracking process, the code is as follows:

class Solution {
    
    
private:
    vector<vector<int>> ans;
    vector<int> res;
public:
    void dfs(vector<int> nums, int index){
    
    
        if(index == nums.size()){
    
    
            ans.emplace_back(res);
            return;
        }
        //不选择当前的数字
        dfs(nums, index + 1);
        //选择当前的数字
        res.emplace_back(nums[index]);
        dfs(nums, index + 1);
        //回溯体现
        res.pop_back();
    }


    vector<vector<int>> subsets(vector<int>& nums) {
    
    
        sort(nums.begin(), nums.end());
        dfs(nums, 0);
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/HERODING23/article/details/108688949