[leetcode] Subsets
2015-01-06 17:21
260 查看
Subsets
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。原容器中的元素在子集中有两种可能,要么在要么不在。因此肯定在一个函数中有两个递归的过程,一个是不放数据,一个是放数据。如此一直递归,直到原容器的大小时递归结束。
题解:
vector<vector<int> > subsets(vector<int> &S) { vector <int> temp; vector<vector<int> >ans; ans.push_back(temp); //Enters null set int len=S.size(); int len2; if(len==0) return ans; sort(S.begin(),S.end()); for(int i=0 ; i<len ; i++) //Traverses the whole input array { len2=ans.size(); // Since we cannot append the new number along with the null set therefore this is done outside the loop temp.clear(); temp.push_back(S[i]); ans.push_back(temp); for(int j=1 ; j<len2 ; j++) { vector<int> temp2(ans[j]); temp2.push_back(S[i]); ans.push_back(temp2); } } return ans; }
View Code
相关文章推荐
- LeetCode Online Judge:Given a set of distinct integers, S, return all possible subsets.
- leetcode题解-78. Subsets && 90. Subsets II
- Leetcode | Partition to K Equal Sum Subsets
- LeetCode[Backtracking]: Subsets
- LeetCode 78 Subsets
- 递归-数组的子集:leetcode 78 Subsets
- LeetCode: Subsets
- [LeetCode] 78. Subsets
- Leetcode NO.78 Subsets
- leetcode 078 —— Subsets
- Leetcode_subsets-ii
- LeetCode:Subsets
- LeetCode:Subsets
- LeetCode---Subsets
- LeetCode:Subsets I II
- LeetCode:Subsets I II
- [LeetCode]Subsets
- LeetCode刷题【Array】 Subsets
- leetcode:Subsets
- 33 leetcode - Subsets