Given a set of distinct integers, S, return all possible subsets.
Note:
For example,
If S = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]Analysis:
DFS
这个就是排列组合中的排列问题。递归如下逻辑:
Func Generate
对于输入字符串s的每一位字符
选取该字符到子集合中,并输出
如果,当前字符不是最后一位字符
递归调用Generate,处理下一位字符
Java
public class Solution { List<List<Integer>> result; List<Integer> solu; public List<List<Integer>> subsets(int[] S) { result = new ArrayList<>(); solu = new ArrayList<>(); Arrays.sort(S); getSubset(S, 0); return result; } public void getSubset(int []S, int st){ if(solu.size()<=S.length){ result.add(new ArrayList<>(solu)); } for(int i=st; i<S.length;i++){ solu.add(S[i]); getSubset(S, i+1); solu.remove(solu.size()-1); } } }
C++
class Solution { public: void genSet(vector<int> &S, vector<vector<int>> &result, vector<int> &solution,int level){ for(int i=level; i<S.size(); i++){ solution.push_back(S[i]); result.push_back(solution); if(i<S.size()-1){ genSet(S,result,solution,i+1); } solution.pop_back(); } } vector<vector<int> > subsets(vector<int> &S) { vector<vector<int>> result; vector<int> solution; if(S.size() == 0) return result; result.push_back(solution); sort(S.begin(), S.end()); genSet(S,result, solution,0); return result; } };