78. Subsets

Posted ArgenBarbie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了78. Subsets相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

78. Subsets

78. Subsets

78. Subsets

78. Subsets

刷题78. Subsets

Leetcode 78. Subsets