• LeetCode OJ--Subsets II


    https://oj.leetcode.com/problems/subsets-ii/

    求一个集合的子集,但集合中有重复元素。

    求子集的问题,对应着数的二进制,相当于对二进制的一个遍历。

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    class Solution {
    public:
        vector<vector<int> > subsetsWithDup(vector<int> &S) {
            vector<vector<int> > ans;
            if(S.size()==0)
                return ans;
            int num = pow(2,S.size());
            sort(S.begin(),S.end());
            for(int i = 0; i<num; i++)
            {
                vector<int> ansPiece;
                ansPiece = oneSubsetPiece(i,S);
                bool flag = 1;
                for(int j = 1; j<ans.size(); j++)
                {
                    if(ansPiece == ans[j]) flag = 0;
                }
                if(flag == 1)
                    ans.push_back(ansPiece);
            }
            return ans;
        }
        //find the num's binary
        vector<int> oneSubsetPiece(int num,vector<int> &S)
        {
            vector<int> ansPiece;
            int YuShu;
            int ChuShu;
            int index = 0;
            while(num)
            {
                YuShu = num %2;
                num = num/2;
                if(YuShu)
                    ansPiece.push_back(S[index]);
                index++;
            }
            return ansPiece;
        }
    };
    
    int main()
    {
        class Solution sol;
        vector<int> num;
        num.push_back(1);
        num.push_back(2);
        num.push_back(2);
        sol.subsetsWithDup(num);
    }
  • 相关阅读:
    js 与或运算符 || && 妙用(great!!!)
    type of && undefined
    全新框架?微信小程序与React Native的异同之处
    JS-十五章(15.16)
    JS-第十三章
    ValueError: zero-size array to reduction operation maximum which has no identity
    time
    模块
    day8-函数
    day7-format字符串格式化
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3787918.html
Copyright © 2020-2023  润新知