【问题描述】
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],
[]
]
1.【基础知识】
1)图的深度遍历;
2)STL中vector排序。
2【屌丝源码】
class Solution { public: vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> mysubset; if(nums.empty()) return mysubset; int sublen(1),veclen(nums.size()),i; while(sublen<=veclen) // 0.1 单独考虑 { for(i=0;i<=veclen-sublen;i++) { int visited[256] = {0}; visited[i] = 1; DFS(nums,i,sublen-1,visited,mysubset);// 0.1 单独考虑 } sublen++; } } void DFS(vector<int> nums,int top,int sublen,int* visited,vector<vector<int>> &mysubset) // top:待添加元素的上一个元素索引。 // sublen:还需要添加的元素个数。 { if(sublen==0) { vector<int> tmp_vec; for(int i=0;i<256;i++) if(visited[i] == 1) tmp_vec.push_back(nums[i]); mysubset.push_back(tmp_vec); return ; } for(int j = top+1;j<sublen;j++) { visited[j] = 1; DFS(nums,j,sublen-1,visited,mysubset); } } };1)卡壳的地方
a.用while控制for循环数目,没能实现;b.用图的DFS,未能保证正确输出。
3.【源码AC】
// LeetCode, Subsets // 增量构造法,深搜,时间复杂度 O(2^n),空间复杂度 O(n) class Solution { public: vector<vector<int> > subsets(vector<int> &S) { sort(S.begin(), S.end()); // 输出要求有序 vector<vector<int> > result; vector<int> path; subsets(S, path, 0, result); return result; } private: static void subsets(const vector<int> &S, vector<int> &path, int step, vector<vector<int> > &result) { if (step == S.size()) { result.push_back(path); return; } // 不选 S[step] subsets(S, path, step + 1, result); // 选 S[step] path.push_back(S[step]); subsets(S, path, step + 1, result); path.pop_back(); } };4.【复盘】
Really Really Manu !Awful frustrated Manu Rem !
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u013630349/article/details/47121697