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], [] ]
给定一个无重复的数字集合,返回所有该集合的自己,要求
class Solution { public: void dfs(vector<vector<int> >&result, vector<int>combination, vector<int>&candidates, int kth, int k, int index2add){ // 当前正在确定组合中的第kth个数,将把候选集candidates中index2add索引位的值作为第kth个数加到组合中 combination.push_back(candidates[index2add-1]); if(kth==k){ result.push_back(combination); } else{ for(int i=index2add+1; i+(k-kth-1)<=candidates.size(); i++){ dfs(result, combination, candidates, kth+1, k, i); } } } vector<vector<int> > getKsubset(vector<int> &S, int k){ // 获得k元子集合 vector<vector<int> >result; vector<int> combination; for(int i=1; i+(k-1)<=S.size(); i++){ dfs(result, combination, S, 1, k, i); } return result; } vector<vector<int> > subsets(vector<int> &S) { vector<vector<int> >result; //一定有一个空集 vector<int> nonVector; result.push_back(nonVector); int size=S.size(); if(size==0)return result; //排序 sort(S.begin(), S.end()); for(int k=1; k<=size; k++){ //依次找k元组合 vector<vector<int> >ksubsets = getKsubset(S, k); result.insert(result.end(), ksubsets.begin(), ksubsets.end()); } return result; } };
LeetCode: Subsets [078],布布扣,bubuko.com
原文地址:http://blog.csdn.net/harryhuang1990/article/details/27525767