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

[leetcode-90-Subsets II]

时间:2017-06-04 00:18:11      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:lin   under   color   track   blog   ==   pop   ++   backtrack   

Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: 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],
[]
]

思路:

与不含重复元素相比,只是添加了一句代码验证一下。

void getsubset(vector<vector<int>>& subs,vector<int>& sub,vector<int>& nums,int start)
{
  subs.push_back(sub);
  for(int i= start;i<nums.size();i++)
  {
    if(i==start || nums[i] != nums[i-1])
    {
      sub.push_back(nums[i]);
      getsubset(subs,sub,nums,i+1);
      sub.pop_back();
    }
  }
}
vector<vector<int>> subsetsWithDup(vector<int>& nums)
{
  vector<vector<int>> subs;
  vector<int>sub;
  sort(nums.begin(),nums.end());
  getsubset(subs,sub,nums,0);
  return subs;
}

参考:

https://discuss.leetcode.com/topic/13543/accepted-10ms-c-solution-use-backtracking-only-10-lines-easy-understand

[leetcode-90-Subsets II]

标签:lin   under   color   track   blog   ==   pop   ++   backtrack   

原文地址:http://www.cnblogs.com/hellowooorld/p/6938909.html

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