Leetcode Subsets

原创 2013年12月05日 18:00:35

dfs again!

记得先排序,同时还要记录当前所在的位置,递归的下一层直接从这个位置开始遍历。

class Solution {
public:
    vector<vector<int> > subsets(vector<int> &S) {
        ans.clear();
        ans.push_back(v);
        sort(S.begin(), S.end());
        for(int i = 1; i <= S.size(); i++){
            v.clear();
            dfs(S, 0, 0, i);
        }
        return ans;
    }
    void dfs(vector<int> &S, int index, int cnt, int sum){
        if(cnt == sum){
            ans.push_back(v);
            return ;
        }
        for(int i = index; i < S.size(); i++){
            v.push_back(S[i]);
            dfs(S, i+1, cnt+1, sum);
            v.pop_back();
        }
    }
    vector<int> v;
    vector<vector<int> > ans;
};


相关文章推荐

Leetcode : Subsets II

URL:https://leetcode.com/problems/subsets-ii/#/description题目大意:Given a collection of integers that m...

leetcode 90. Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets. ...

【leetcode】90. Subsets II

leetcode, subsets ||, 3种解法

leetcode:暴力枚举法之Subsets II

leetcode:暴力枚举法之Subsets II 题目; Given a collection of integers that might contain duplicates, S, retur...

LeetCode OJ:Subsets II

Subsets II   Given a collection of integers that might contain duplicates, S, return all possible...

leetcode-78 Subsets

分析:求集合的所有子集问题。题目要求子集中元素非递减序排列,因此我们先要对原来的集合进行排序。原集合中每一个元素在子集中有两种状态:要么存在、要么不存在。这样构造子集的过程中每个元素就有两种选择方法:...
  • sole_cc
  • sole_cc
  • 2015年03月28日 19:19
  • 378

[leetcode 78 & 90, Medium] Subsets I and II

Subsets I and II

Subsets II -- leetcode

Given a collection of integers that might contain duplicates, S, return all possible subsets. Not...

leetcode 90 Subsets II

leetcode 90 Subsets II c++ Python

[LeetCode][Java] Subsets II

题目: Given a collection of integers that might contain duplicates, nums, return all possible sub...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Leetcode Subsets
举报原因:
原因补充:

(最多只允许输入30个字)