Leetcode - 078. Subsetssegmentfault
這道題重定義了什麼叫可行解:
通常而言,可行解須要知足強約束性條件集,而本題的可行解就是單一弱約束性條件(distinct integers,只須要當前集合內的元素不重複便可算做一個可行解) ,算是比較簡單的入門級dfs + backtracing 題目。code
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 IIci
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; } };