[leetcode-78]Subsets

Description

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],
  []
]

Solution

core idea:

  1. pick one element and pass the elements not picked before to next iteration.
class Solution {
     
public:
    vector<vector<int>> subsets(vector<int>& nums) {
     
        vector<vector<int>> result;
        vector<int> empty;
        result.push_back(empty);
        
        if(nums.size() == 0) {
     
            return result;
        }
        
        for(int i = 1; i <= nums.size(); i++) {
     
            vector<int> record;
            powerset(result, record, nums, i);
        }
        
        return result;
    }
    
    void powerset(vector<vector<int>> &result, vector<int> &select, vector<int> &left, int count) {
     
        if(select.size() == count){
     
            result.push_back(select);
            return;
        }
        
        // select[] left[1,2,3,4]
        // select[1] left[2,3,4]
        // select[2] left[3,4]
        // select[3] left[4]
        // select[4] left[]
        
        for(int i = 0; i < left.size(); i++) {
     
            select.push_back(left[i]);
            vector<int> temp = left;
            temp.erase(temp.begin(), temp.begin() + i + 1);
            
            if(temp.size() + select.size()>= count) {
     
                powerset(result, select, temp, count);
            }
            
            select.pop_back();     
        }
        
        
    }
};

你可能感兴趣的:(leetcode,leetcode)