码迷,mamicode.com
首页 > 其他好文 > 详细

<LeetCode OJ> 78. Subsets

时间:2016-03-10 12:50:36      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

Total Accepted: 87879 Total Submissions: 285264 Difficulty: Medium

Given a set of distinct integers, nums, 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 nums = [1,2,3], a solution is:

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

Subscribe to see which companies asked this question

Hide Similar Problems
 (M) Generalized Abbreviation

分析:

本题上上一篇博客的题目基本一样的,主要区别在于有一个动态的size,并且确定答案的方式不一样。(本题是用len作为答案的依据)

class Solution {
public:
    void dfs(vector<int>& nums, vector<int> &subres, int start, int len)//使用引用,有利于防止内存大爆炸  
    {  
        if (subres.size() == len)//已经获得答案,并且回溯  
        {  
            result.push_back(subres);   
            return;//回溯  
        }  
        for (int i = start; i < nsize; i++)  
        {  
            subres.push_back(nums[i]);  
            dfs(nums, subres, i + 1, len);  
            subres.pop_back(); // 回溯去掉末尾元素  
        }  
    }
    vector<vector<int>> subsets(vector<int>& nums) {
        nsize=nums.size();
        if ( nums.size() == 0)   
            return result; 
        sort(nums.begin(),nums.end());    
        vector<int> subres;  
        for(int len=0; len<=nums.size() ;len++)
            dfs(nums, subres, 0, len);  
        return result;  
    }
    
private:
    vector<vector<int > > result;
    int nsize;
};



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50844984

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

<LeetCode OJ> 78. Subsets

标签:

原文地址:http://blog.csdn.net/ebowtang/article/details/50844984

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!