xinyu04

导航

LeetCode 78 Subsets 回溯

Given an integer array nums of unique elements, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Solution

求一个数组的所有子集。使用 \(\text{Backtracking}\) 即可。我们用一个 \(st\) 来记录起始,防止出现重复的组合。最后记得复原操作 \(pop\_back\)

点击查看代码
class Solution {
private:
    vector<vector<int>> ans;
    vector<int> track;
    void backtrack(vector<int> nums, int st, vector<int>& track){
        
        ans.push_back(track);
        
        for(int i=st;i<nums.size();i++){
            track.push_back(nums[i]);
            backtrack(nums, i+1, track);
            // remove
            track.pop_back();
        }
        
    }
    
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        backtrack(nums, 0, track);
        return ans;
    }
};

posted on 2022-07-23 21:07  Blackzxy  阅读(14)  评论(0编辑  收藏  举报