码迷,mamicode.com
首页 > 其他好文 > 详细

78. Subsets

时间:2016-03-26 18:46:28      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

Given a set of distinct integers, nums, return all possible subsets.

Note:

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.

 

For example,
If nums = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

1.递归
class Solution {
public:
    void getSubsets(vector<vector<int>> &res, vector<int> nums, vector<int> v, int n, int m, int k, int idx)
    {
        if(k == m)
        {
            res.push_back(v);
            v.clear();
            return;
        }
        for(int i = idx; i < n; i++)
        {
            v.push_back(nums[i]);
            getSubsets(res, nums, v, n, m, k+1, i+1);
            v.pop_back();
        }
    }
    
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> v;
        res.push_back(v);
        int n = nums.size(), i;
        if(0 == n)
            return res;
        sort(nums.begin(), nums.end());
        for(i = 1; i <= n; i++)
        {
            getSubsets(res, nums, v, n, i, 0, 0);
        }
        return res;
    }
};

 



2.非递归
class Solution {
public:
    void getSubsets(vector<vector<int>> &res, vector<int> nums, int n, int m)
    {
        vector<int> d;
        int i, j;
        for(i = 0; i < n; i++)
        {
            d.push_back((i < m) ? 1 : 0);
        }
        while(1)
        {
            vector<int> v;
            for(i = 0; i < n; i++)
            {
                if(d[i])
                    v.push_back(nums[i]);
            }
            res.push_back(v);
            
            //find [1, 0] pattern
            bool found = false;
            int ones = 0;
            for(i = 0; i < n-1; i++)
            {
                if(1 == d[i] && 0 == d[i+1])
                {
                    d[i] = 0;
                    d[i+1] = 1;
                    found = true;
                    for(j = 0; j < i; j++)
                    {
                        d[j] = (ones > 0) ? 1 : 0;
                        ones--;
                    }
                    break;
                }
                if(1 == d[i])
                    ones++;
            }
            if(!found)
                break;
        }
    }
    
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> v;
        res.push_back(v);
        int n = nums.size(), i;
        if(0 == n)
            return res;
        sort(nums.begin(), nums.end());
        for(i = 1; i <= n; i++)
        {
            getSubsets(res, nums, n, i);
        }
        return res;
    }
};

 

78. Subsets

标签:

原文地址:http://www.cnblogs.com/argenbarbie/p/5323397.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!