Given a set of distinct integers, S, 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 S = [1,2,3], a solution is: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
DFS 的简单应用 : 求组合
class Solution { public: void DFS(vector<int> &S, vector<int> &temp,int n, int size,int start) { if(n == size) { result.push_back(temp); return ; } if(n > size) return ; for(int i = start; i< len ;i++) { if(flag[i] == false) { flag[i] = true; temp.push_back(S[i]); DFS(S, temp, n+1, size,i+1); temp.pop_back(); flag[i] = false; } } } vector<vector<int> > subsets(vector<int> &S) { // Start typing your C/C++ solution below // DO NOT write int main() function result.clear(); len = S.size(); flag.resize(len,false); vector<int> temp; result.push_back(temp) ; sort(S.begin(), S.end()); for(int i = 1; i <= len ; i++) DFS(S, temp,0, i,0); return result; } private: vector<vector<int> > result ; vector<bool> flag; int len; };
解释下start,因为组合和排列不同,组合不考虑排序,所以必须给元素进入temp指定一个次序,这个规则定义就是通过start,这样保证temp是有序的,也就保证result中没有重复
重写后的代码:
class Solution { public: void DFS(vector<int> &S, int currentSize, int length, int currentPos, vector<int> &ans) { if(length == currentSize){ res.push_back(ans); return; } for(int i = currentPos; i < S.size(); i++) { ans.push_back(S[i]); DFS(S, currentSize, length + 1, i+1, ans); ans.pop_back(); } } vector<vector<int> > subsets(vector<int> &S) { // Start typing your C/C++ solution below // DO NOT write int main() function sort(S.begin(), S.end()); res.clear(); vector<int> empt; res.push_back(empt); for(int i = 1; i <= S.size(); i++) { vector<int> ans; DFS(S, i, 0, 0, ans); } return res; } private: vector<vector<int>> res; };