您的位置:首页 > 其它

leetcode笔记:Subsets II

2015-12-29 23:48 260 查看
一. 题目描述

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:

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


二. 题目分析

该题相比Subsets一题略有不同,该题在给定的数组中,允许出现重复的元素。但最后输出的排列不能有重复的组合。因此,在DFS时,使用一个数组temp来记录某个数是否被使用过即可。

三. 示例代码

[code]#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    vector<vector<int> > subsetsWithDup(vector<int> nums) {
        sort(nums.begin(), nums.end());
        subsets(nums, 0);
        return result;
    }

private:
    vector<int> temp;
    vector<vector<int> > result;

    void subsets(vector<int> nums, int index){
        if(index == nums.size()) 
        { 
            result.push_back(temp);
            return;
        }
        if(temp.size() == 0 || temp[temp.size()-1] != nums[index])
            subsets(nums, index + 1);    
        temp.push_back(nums[index]);
        subsets(nums, index + 1);
        temp.pop_back();
    }
};


四. 小结

该题需要注意的地方是,避免出现同样的排列组合。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: