LeetCode Online Judge:Given a set of distinct integers, S, return all possible subsets.
2015-01-07 21:43
357 查看
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 =
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], [] ]
解答:考虑采用递归的思想,先对输入排序,再进行递归
class Solution { public: vector<vector<int> > subsets(vector<int> &S) { int len=S.size(); sort(S.begin(),S.end()); vector<vector<int> > result; result=test(S,len); return result; } private: vector<vector<int>> test(vector<int> S,int len) { vector<vector<int>> out; vector<vector<int>> result; vector<int> tmp; vector<int> temp; int elment; if(len==0) { out.push_back(tmp); return out; } else if(len==1) { out.push_back(tmp); tmp.push_back(S[0]); out.push_back(tmp); return out; } else { elment=S[len-1]; out=test(S,len-1); for(int i=0;i<out.size();i++) { result.push_back(out[i]); temp=out[i]; temp.push_back(elment); result.push_back(temp); } return result; } } };
相关文章推荐
- Given an array of size n, find all the possible sub set of the array of size k
- 输出一个集合所有子集的元素和(Print sums of all subsets of a given set)
- Write a method that returns all subsets of a set.
- Halfway to go, though I have finished 145 questions of leetcode online judge
- LeetCode Online Judge 题目C# 练习 - Length of Last Word
- Write a method that returns all subsets of a set
- Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral or
- Given an array of integers, return indices of the two numbers such that they add up to a specific ta
- Generate all possible sorted arrays from alternate elements of two given sorted arrays
- Algorithm_Write a method that returns all subsets of a set.
- LeetCode Online Judge 题目C# 练习 - Subsets
- CareerCup Given a binary matrix of N X N of integers , you need to return only unique rows of binary
- Q9.4 Write a method that returns all subsets of a set.
- Print all possible strings of length k that can be formed from a set of n characters
- LeetCode Online Judge 题目C# 练习 - Median of Two Sorted Arrays
- Given an array of numbers, return array of products of all other numbers (no division)
- 给出一个set的字符和一个正数k,求所有由这个set能组成长度为k的字符串集合 print-all-combinations-of-given-length
- Ch8.3: find all the subsets of a set
- Given an integer, return all sequences of numbers that sum to it
- Given a non-empty array of integers, return the k most frequent elements.