【演算法】【搜尋和回溯】Leetcode子集
阿新 • • 發佈:2020-08-16
78. 子集
題目連結:https://leetcode-cn.com/problems/subsets/
class Solution { public: vector<vector<int>> res; vector<int> path; vector<vector<int>> subsets(vector<int>& nums) { dfs(nums, 0); return res; } void dfs(vector<int>& nums, int u) { res.push_back(path); for(int i = u; i < nums.size(); i++) { path.push_back(nums[i]); dfs(nums, i + 1); path.pop_back(); } } };
90. 子集II
題目連結:https://leetcode-cn.com/problems/subsets-ii/
class Solution { public: vector<vector<int>> res; vector<int> path; vector<vector<int>> subsetsWithDup(vector<int>& nums) { sort(nums.begin(), nums.end()); dfs(nums, 0); return res; } void dfs(vector<int>& nums, int u) { res.push_back(path); for(int i = u; i < nums.size(); i++) { if(i > u && nums[i] == nums[i - 1]) continue; path.push_back(nums[i]); dfs(nums, i + 1); path.pop_back(); } } };