• [LeetCode]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.

     

    For example,
    If S = [1,2,3], a solution is:

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

    思考:最后还是按上一题的思路来k=0:n

    class Solution {
    private:
        vector<vector<int> > res;
        vector<int> ans;
    public:
        void DFS(vector<int> S,int n,int start,int dep,int k)
        {
            if(dep==k)
            {
                res.push_back(ans);
                return;
            }
            for(int i=start;i<n-k+1;i++)
            {
                ans.push_back(S[i+dep]);
                DFS(S,n,i,dep+1,k);
                ans.pop_back();
            }
        }
        vector<vector<int> > subsets(vector<int> &S) {
            res.clear();
            ans.clear();
            int n=S.size();
            sort(S.begin(),S.end());
            for(int k=0;k<=n;k++)
            {
                DFS(S,n,0,0,k); //上一题的k
            }
            return res;
        }
    };
    

    second time:

    class Solution {
    public:
        void DFS(vector<vector<int> > &res, vector<int> &ans, vector<int> &S, int dep, int start)
        {
            res.push_back(ans);
            if(dep == S.size()) return;
            for(int i = start; i < S.size(); ++i)
            {
                ans.push_back(S[i]);
                DFS(res, ans, S, dep + 1, i + 1);
                ans.pop_back();
            }
        }
        vector<vector<int> > subsets(vector<int> &S) {
            vector<vector<int> > res;
            vector<int> ans;
            sort(S.begin(), S.end());
            DFS(res, ans, S, 0, 0);
            return res;
        }
    };
    

      

      

  • 相关阅读:
    用导数解决逗逼初三数学二次函数图像题
    NOIP 2014 pj & tg
    BZOJ 1004
    双参数Bellman-ford带队列优化类似于背包问题的递推
    emu1
    無題
    15 day 1代碼
    javascript quine
    线段树的总结
    Watering the Fields(irrigation)
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3520714.html
Copyright © 2020-2023  润新知