【问题描述】
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排序。
3)有了这个图就不必再多说算法思想了,当然,如果将根节点置空,下面各节点置为(0,1)组合,表现将会更直观。总而言之,言而总之,算法思想如下图。2【屌丝源码】
#include <iostream>
#include<vector>
#include<list>
#include<algorithm>
#include <iterator> // std::next
using namespace std;
/*
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);
}
}
};
*/
// 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(); // 清空原来的路径
}
};
int main(int argc, char* argv[])
{
Solution mysln;
int tmp;
vector<int> myvec;
while(cin>>tmp)
myvec.push_back(tmp);
sort(myvec.begin(),myvec.end());
vector<vector<int>> subsets = mysln.subsets(myvec);
for(int i = 0;i<subsets.size();i++)
{
for(int j = 0;j<subsets[i].size();j++)
cout<<subsets[i][j]<<' ';
cout<<endl;
}
return 0;
}
卡壳的地方
a.试图用while控制for循环数目,没能实现;b.用图的DFS思想,未能保证正确输出。
3.【源码AC】
<pre name="code" class="cpp">// 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 Manu Day !Frustrated Manu Rem !