标签:
Given a set of distinct integers, nums, return all possible subsets.
Note:
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
分析:
本题上上一篇博客的题目基本一样的,主要区别在于有一个动态的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
标签:
原文地址:http://blog.csdn.net/ebowtang/article/details/50844984