【LeetCode】 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],
  []
]

思路一:迭代法

Using [1, 2, 3] as an example, the iterative process is like:

 

  1. Initially: [[]]
  2. Adding the first number to all the existed subsets: [[], [1]];
  3. Adding the second number to all the existed subsets: [[], [1], [2], [1, 2]];
  4. Adding the third number to all the existed subsets: [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> res(1, vector<int>());
        for(int i = 0; i<nums.size();++i){
            int size = res.size();
            vector<int> sub;
            for(int j = 0;j<size;++j){
                sub = res[j];
                sub.push_back(nums[i]);
                res.push_back(sub);
                
            }
        }
        return res;
    }
};

 

思路二:递归法

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> sub;
        backtracking(0, nums, res, sub);
        return res;
    }
    
    void backtracking(int start, vector<int>& nums, vector<vector<int>>& subs, vector<int>& sub){
        subs.push_back(sub);
        for(int i = start;i<nums.size(); ++i){
            sub.push_back(nums[i]);
            backtracking(i+1, nums, subs, sub);
            sub.pop_back();
        }
    }
};

利用迭代的思路可以解决一系列的排列组合的问题,比如:

Subset II

描述:

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

思路:

class Solution {
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> sub;
        sort(nums.begin(), nums.end());
        backtracking(0,nums,res,sub);
        return res;
    }
    
    void backtracking(int start, vector<int>& nums, vector<vector<int>>& subs, vector<int>& sub){
        subs.push_back(sub);
        for(int i = start;i<nums.size();++i){
            if(i>start && nums[i] == nums[i-1]) continue;
            sub.push_back(nums[i]);
            backtracking(i+1, nums, subs, sub);
            sub.pop_back();
        }
    }
};

 

posted @ 2018-10-26 08:59  华不摇曳  阅读(370)  评论(0编辑  收藏  举报