Wednesday, September 25, 2013

Subsets

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

A:

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> tmp;
        res.push_back(tmp);
        
        for(auto v : nums)
        {
            int n = res.size();
            for(int i =0;i<n;++i)
            {
                vector<int> tmp = res[i];
                tmp.push_back(v);
                res.push_back(tmp);
            }
        }
        return res;
    }
};

Mistakes:


No comments:

Post a Comment