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.

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

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

    上一题不一样的是,现在的结果里,是给定数组的所有的组合可能,长度可以是0,1,到 n。例如给定S=[1,2] 那么结果是{[],[1],[2],[1,2]}升序排列。

    机智的想到了运用上一题的子函数。还是回溯法。

    这里的start不是具体的数字,而是给定数组的下标,所以从0开始。那么这里的k就是从0到S.size遍历一下了。因为空的可以先输入,所以k就从1开始吧。

    class Solution {
    public:
        void dfs78(vector<vector<int> > &ans, vector<int> subans, vector<int> &S, int start, int k)
        {
            if (subans.size() == k)
            {
                ans.push_back(subans); return ;
            }
            for (int i = start; i < S.size(); i++)
            {
                subans.push_back(S[i]);
                dfs78(ans, subans, S, i + 1, k);
                subans.pop_back();
            }
        }
        vector<vector<int> > subsets(vector<int> &S) {
            vector<vector<int> > ans;
            vector<int> empty; 
            ans.push_back(empty);
            if (S.size() == 0) return ans;
            sort(S.begin(), S.end());
            for (int k = 1; k <= S.size(); k++)
            {
                vector<int> subans;
                dfs78(ans, subans, S, 0, k);
            }
            return ans;
        }
    };
  • 相关阅读:
    C3线性化
    fingerprint for the ECDSA key
    tmp
    线性筛(欧拉筛)
    tmp
    tmp
    Micro Frontends 微前端
    TreeFrog Framework : High-speed C++ MVC Framework for Web Application http://www.treefrogframework.org
    消息同屏转发
    web-linux-shell实现 阿里方案canvas+wss。
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4102525.html
Copyright © 2011-2022 走看看