-
39. 组合总和
-
class Solution { public:vector<vector<int>>b; vector<int>a; void dfs(vector<int>& candidates, int target,int sum,int s){ if(target<sum) return ; if(target==sum){ b.push_back(a); return ; } for(int i=s;i<candidates.size();i++){ a.push_back(candidates[i]); dfs(candidates,target,sum+candidates[i],i); a.pop_back(); } } vector<vector<int>> combinationSum(vector<int>& candidates, int target) { dfs(candidates,target,0,0); return b; } };
-
40.组合总和II
-
class Solution { public: vector<vector<int>> b; vector<int> a; void dfs(vector<int>& candidates, int target, int sum, int s,vector<bool>& mark) { if (sum > target) return; if (sum == target) { b.push_back(a); return; } for (int i = s ; i < candidates.size(); i++) { if(i > 0 && candidates[i] == candidates[i - 1] && !mark[i-1]) continue; a.push_back(candidates[i]); mark[i] = 1; dfs(candidates, target, sum + candidates[i], i+1, mark); a.pop_back(); mark[i] = 0; } } vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<bool> mark(candidates.size(), 0); sort(candidates.begin(), candidates.end()); dfs(candidates, target, 0, 0, mark); return b; } };
-
131.分割回文串
-
class Solution { public: vector<vector<string>> b; vector<string> a; bool huiwen(string s, int l, int r) { if (l == r) return 1; for (; l < r; l++, r--) { if (s[l] != s[r]) return 0; } return 1; } void dfs(string s, int k) { if (k >= s.size()) { b.push_back(a); return; } for (int i = k; i < s.size(); i++) { string q(s.begin() + k, s.begin() + i+1); if (huiwen(s, k, i)) { cout<<q<<" "; a.push_back(q); dfs(s, i + 1); a.pop_back(); } } } vector<vector<string>> partition(string s) { dfs(s, 0); return b; } };