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], [] ]
解题分析:
每个元素,都有两种选择,选或者不选。
为了保持子集有序,必须首先对原数组sort
class Solution { public: vector<vector<int> > subsets(vector<int> &S) { vector<vector<int>> result; if (S.size() == 0) return result; sort(S.begin(), S.end()); // sort vector<int> path; dfs(S, path, 0, result); return result; } void dfs(const vector<int>& S, vector<int>&path, int cur, vector<vector<int>>& result) { if (cur == S.size()) { result.push_back(path); return; } // not choose S[cur] dfs(S, path, cur + 1, result); // choose S[cur] path.push_back(S.at(cur)); dfs(S, path, cur + 1, result); path.pop_back(); } };
Given a collection of integers that might contain duplicates, 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,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
解题分析:
这题有重复元素,但本质上,跟上一题很类似,上一题中元素没有重复,相当于每个元素只能选0或1次,这里扩充到了每个元素可以选0到若干次而已
class Solution { public: vector<vector<int> > subsetsWithDup(vector<int> &S) { vector<vector<int>> result; if (S.size() == 0) return result; sort(S.begin(), S.end()); vector<int> path; dfs(S, path, 0, result); return result; } void dfs(const vector<int>& S, vector<int>& path, int cur, vector<vector<int>>& result) { result.push_back(path); for (int i = cur; i < S.size(); ++i) { if (i != cur && S.at(i) == S.at(i-1)) { continue; } path.push_back(S.at(i)); dfs(S, path, i + 1, result); path.pop_back(); } } };
Leetcode:Subsets 子集生成
时间: 2024-08-26 22:00:35