zoukankan      html  css  js  c++  java
  • (LeetCode 78)SubSets

    Given a set of distinct integers, S, return all possible subsets.

    Note:

    • Elements in a subset must be in non-descending order.
    • The solution set must not contain duplicate subsets.

    image

    题目要求 :

    求整数数组的所有子集

    注意:

    1、子集元素按非降序排列

    2、不包含重复的子集

    解题思路:

    求解这类诸如子集的题目,都可以采用回溯法。(剪枝+递归)

    代码如下:

    class Solution {
    private:
        vector<vector<int> > ans;
    public:
        void collectSubSet(vector<int> &S,vector<int> x,int len,int idx){
            if(idx==len){
                vector<int> subset;
                for(int i=0;i<len;i++){
                    if(x[i]!=0)
                        subset.push_back(S[i]);
                }
                sort(subset.begin(),subset.end(),less<int>());
                ans.push_back(subset);
                return;
            }
            x[idx]=0;
            collectSubSet(S,x,len,idx+1);
            x[idx]=1;
            collectSubSet(S,x,len,idx+1);
        }
    
        vector<vector<int> > subsets(vector<int> &S) {
            int len=S.size();
            vector<int> x(len);
     //       sort(S.begin(),S.end(),greater<int>());
            collectSubSet(S,x,len,0);
    //        sort(ans.begin(),ans.end(),cmp());
            return ans;
        }
    };
  • 相关阅读:
    详解 注解
    线段树分治
    实用Trick
    CF932F(李超线段树+dp)
    CF24D Broken robot(高斯消元)
    LCT学习笔记
    [HNOI2008]GT考试
    [AHOI2009]中国象棋
    [APIO2012]派遣
    CF961G Partitions
  • 原文地址:https://www.cnblogs.com/AndyJee/p/4456720.html
Copyright © 2011-2022 走看看