[LeetCode]90.Subsets II

简介:

题目

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

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

思路

78.Subsets的唯一区别就是添加了两行去重的代码。

代码

    /**------------------------------------
    *   日期:2015-03-01
    *   作者:SJF0115
    *   题目: 90.Subsets II
    *   网址:https://oj.leetcode.com/problems/subsets-ii/
    *   结果:AC
    *   来源:LeetCode
    *   博客:
    ---------------------------------------**/
    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;

    class Solution {
    public:
        vector<vector<int> > subsetsWithDup(vector<int> &S) {
            int size = S.size();
            vector<vector<int> > result;
            vector<int> path;
            // 排序
            sort(S.begin(),S.end());
            // 空集
            result.push_back(path);
            // 其他子集
            for(int i = 1;i <= size;++i){
                DFS(S,size,i,0,path,result);
            }//for
            return result;
        }
    private:
        // s源数据集 n源数据个数 k子集长度 index为第index个元素 path路径 result最终结果
        void DFS(vector<int> &s,int n,int k,int index,vector<int> &path,vector<vector<int> > &result){
            // 一个子集
            if(path.size() == k){
                result.push_back(path);
                return;
            }//if
            for(int i = index;i < n;++i){
                // 去重
                if(i != index && s[i] == s[i-1]){
                    continue;
                }//if
                path.push_back(s[i]);
                DFS(s,n,k,i+1,path,result);
                path.pop_back();
            }//for
        }
    };

    int main(){
        Solution s;
        vector<int> num = {1,2,2};
        vector<vector<int> > result = s.subsetsWithDup(num);
        // 输出
        for(int i = 0;i < result.size();++i){
            for(int j = 0;j < result[i].size();++j){
                cout<<result[i][j]<<" ";
            }//for
            cout<<endl;
        }//for
        return 0;
    }

运行时间

这里写图片描述

目录
相关文章
LeetCode 90. Subsets II
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
51 0
LeetCode 90. Subsets II
|
Python
[LeetCode] Subsets
Recursive (Backtracking) This is a typical problem that can be tackled by backtracking. Since backtracking has a more-or-less similar template, so I do not give explanations for this method.
763 0
|
2天前
【LeetCode刷题】前缀和解决问题:742.寻找数组的中心下标、238.除自身以外数组的乘积
【LeetCode刷题】前缀和解决问题:742.寻找数组的中心下标、238.除自身以外数组的乘积
|
2天前
【LeetCode刷题】二分查找:寻找旋转排序数组中的最小值、点名
【LeetCode刷题】二分查找:寻找旋转排序数组中的最小值、点名
|
2天前
|
索引
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
|
2天前
【LeetCode刷题】专题三:二分查找模板
【LeetCode刷题】专题三:二分查找模板
【LeetCode刷题】专题三:二分查找模板