Leetcode - Subsets I,II
这道题重定义了什么叫可行解:
一般而言,可行解需要满足强约束性条件集,而本题的可行解就是单一弱约束性条件(distinct integers,只需要当前集合内的元素不重复即可算作一个可行解) ,算是比较简单的入门级dfs + backtracing 题目。
class Solution { public: void dfs(vector<vector<int>> & vct,vector<int> &cur,vector<int>& nums,int index) { vct.push_back(cur); int n = nums.size(); if(index >= n) return; for(int i = index;i < n;++i) { cur.push_back(nums[i]); dfs(vct,cur,nums,i + 1); cur.pop_back(); } } vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> vct; vector<int> cur; dfs(vct,cur,nums,0); return vct; } };
diff vs the pre version:
有重复的元素怎么算?相关的思路雷同于Leetcode - 040. Combination Sum II
class Solution { public: void dfs(vector<vector<int>> &vct, vector<int> &cur, vector<int>& nums,vector<int> & used,int index) { vct.push_back(cur); int n = nums.size(); if (index >= n) return; for (int i = index; i < n; ++i) { if (used[i] == 0) { int j = i - 1; bool repeated = false; while (j >= 0 && nums[j] == nums[i]) { if (used[j] == 0) { repeated = true; break; } --j; } if (repeated) continue; cur.push_back(nums[i]); used[i] = 1; dfs(vct, cur, nums, used, i + 1); used[i] = 0; cur.pop_back(); } } } vector<vector<int>> subsetsWithDup(vector<int>& nums) { vector<vector<int>> vct; vector<int> cur; int n = nums.size(); if (n <= 0) return vct; vector<int> used(n, 0); sort(nums.begin(), nums.end()); dfs(vct, cur, nums,used,0); return vct; } };
相关推荐
aanndd 2020-08-12
aanndd 2020-07-26
aanndd 2020-07-08
zangdaiyang 2020-07-04
yaohustiAC 2020-06-28
us0 2020-06-28
yaohustiAC 2020-06-28
zangdaiyang 2020-06-28
Clairezz 2020-06-28
嗡汤圆 2020-06-26
嗡汤圆 2020-06-21
aanndd 2020-06-16
aanndd 2020-06-16
码墨 2020-06-16
yaohustiAC 2020-06-11
zangdaiyang 2020-06-10
jiayuqicz 2020-06-09
yaohustiAC 2020-06-06
heray0 2020-06-04