【Subsets II】cpp

题目:

Given a collection of integers that might contain duplicates, 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,2], a solution is:

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

代码:

class Solution {
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
            std::sort(nums.begin(), nums.end());
            vector<vector<int> > ret;
            vector<int> tmp;
            Solution::dfs(ret, nums, 0, tmp);
            return ret;
    }
    static void dfs(vector<vector<int> >& ret, vector<int>& nums, int index, vector<int>& tmp )
    {
            if ( index==nums.size() )
            {
                ret.push_back(tmp);
                return;
            }
            tmp.push_back(nums[index]);
            Solution::dfs(ret, nums, index+1, tmp);
            tmp.pop_back();
            if ( !(tmp.size()>=1 && tmp.back()==nums[index]) )
            {
                Solution::dfs(ret, nums, index+1, tmp);
            }
    }
};

tips:

大体思路与Subsets类似(http://www.cnblogs.com/xbf9xbf/p/4516802.html

经过画图推演:dfs向左边走的条件不变;再向右边走时,如果当前节点的最后一个元素与即将要加入的新元素相同,则不往右边走了。因为再往右边走,右边肯定包含左边的重复子集了。

===================================

再补充一个增量构造法的迭代解法,代码如下:

class Solution {
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
            std::sort(nums.begin(), nums.end());
            vector<vector<int> > ret;
            vector<int> none;
            ret.push_back(none);
            int pureNew = 0;
            for ( size_t i = 0; i < nums.size(); ++i )
            {
                vector<vector<int> > tmp = ret;
                size_t begin = 0;
                if ( i>=1 && nums[i]==nums[i-1] )
                {
                    begin = ret.size()-pureNew;
                }
                for ( size_t j = begin; j < tmp.size(); ++j )
                {
                    tmp[j].push_back(nums[i]);
                    ret.push_back(tmp[j]);
                }
                pureNew = ret.size() - tmp.size();
            }
            return ret;
    }
};

tips:

增加新元素前,判断nums[i]==nums[i-1]的条件是否成立;如果成立,则增量应该只作用于上一轮新增加的子集上,这样保证没有重复的;这个思路也很简洁。

学习了几个blog的思路:

http://bangbingsyb.blogspot.sg/2014/11/leetcode-subsets-i-ii.html

http://www.cnblogs.com/TenosDoIt/p/3451902.html

http://www.cnblogs.com/yuzhangcmu/p/4211815.html

完毕。

时间: 2024-11-04 13:41:29

【Subsets II】cpp的相关文章

【Permutations II】cpp

题目: Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example,[1,1,2] have the following unique permutations:[1,1,2], [1,2,1], and [2,1,1]. 代码: class Solution { public: vector<vector<int>>

【Pascal&#39;s Triangle II 】cpp

题目: Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3,Return [1,3,3,1]. Note:Could you optimize your algorithm to use only O(k) extra space? 代码: class Solution { public: vector<int> getRow(int rowIndex) { vector

【Unique Paths II】cpp

题目: Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. For example, There is one obstacle in the m

【Word Break II】cpp

题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. For example, givens = "catsanddog",dict = ["cat", "cats&q

【Jump Game II 】cpp

题目: Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of j

【Path Sum II】cpp

题目: Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ / 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] 代码: /** * Definition f

【Linked List Cycle II】cpp

题目: Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Follow up:Can you solve it without using extra space? 代码: 使用hashmap版 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNod

【Remove Duplicates from Sorted Array II】cpp

题目: Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For example,Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. 代码: class Solution { public: int removeDuplic

【Spiral Matrix II】cpp

题目: Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example,Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 代码: class Solution { public: vector<vector<