Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums =[1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
Subscribe to see which companies asked this question
题目大意是要求解出一个给定序列的所有子集,即长度为0,1,…n的所有子集,n为给定序列的长度。
这题思想和LeetCode 77类似,使用回溯法可以解决,同样,也要注意去除重复的情况,[1,2]与[2,1]是一样的,这种要剔除。这里由于给定序列里元素是不定的,所以先要排序,之后使用LeetCode 77里的处理方法,每次遍历选择元素时,从i(i = m)到n,之后将nums[i]压入vector,随后以i + 1进入递归,遍历选择元素从i + 1到n。这样就可以保证前面选择到的元素,后面将不会被选中。
subsets中要利用一个循环,以子集长度为循环条件,从0一直选择到n。具体代码如下:
void backtrace(int n, int m, int k, int l, const vector<int> &nums,
vector<int> &rec, vector<vector<int>> &res)
{
if (l == k) {
res.push_back(rec);
return ;
}
else if (m >= n) {
return ;
}
int i;
for (i = m; i < n; ++i) {
rec.push_back(nums[i]);
backtrace(n, i + 1, k, l + 1, nums, rec, res);
rec.pop_back();
}
}
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
vector<int> rec;
sort(nums.begin(), nums.end());
int i;
int sz = (int) nums.size();
for (i = 0; i <= sz; ++i) {
backtrace(sz, 0, i, 0, nums, rec, res);
}
return res;
}
};