给定一个含不同整数的集合,返回其所有的子集
样例
如果 S = [1,2,3],有如下的解:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
代码如下:
class Solution {
public:
/**
* @param nums: A set of numbers
* @return: A list of lists
*/
vector<int> base;
void backtracing(int start, int length, vector<int> &nums, vector<vector<int>> &subset)
{
if(start == length)
{subset.push_back(base); return;}
base.push_back(nums[start]);
backtracing(start+1, length, nums, subset);
base.pop_back();
backtracing(start+1, length, nums, subset);
}
vector<vector<int>> subsets(vector<int> &nums) {
// write your code here
vector<vector<int>> subset;
sort(nums.begin(), nums.end());
//先对nums中的数据进行排序,使得数组中的元素非降序
backtracing(0,nums.size(),nums,subset);
return subset;
}
};