Day27——回溯算法Ⅲ
- 1.组合总和
- 2.组合总和II
- 3.分割回文串
内容
● 39.组合总和
● 40.组合总和II
● 131.分割回文串
1.组合总和
思路:和组合总和一样,先从candidates中遍历选择元素,但是纵向递归时所选择元素要包括当前元素
vector<int> path;vector<vector<int>> res;
public:void backtracking(vector<int>& candidates, int target, int sum, int startIndex) {if(sum > target) return;else if(sum == target) {res.push_back(path);return;}for(int i = startIndex; i < candidates.size(); i++) {sum += candidates[i];path.push_back(candidates[i]);backtracking(candidates, target, sum, i);sum -= path.back();path.pop_back();}}vector<vector<int>> combinationSum(vector<int>& candidates, int target) {backtracking(candidates, target, 0, 0);return res;}
剪枝:集合排序,当sum大于target时,整个for循环退出
2.组合总和II
思路:和上一题的区别在于这个要去重
如何去重,排序后,在for循环遍历时,如果当前元素已经访问,那么下一个和他相等的元素就可以跳过,按照这个思路,在for循环中如果是第一次进入,那么不需要做判断,此后访问元素时,都判断是否和前一个元素相等,如果相等,直接跳过
vector<int> path;vector<vector<int>> res;
public:void backtracking(const vector<int>& candidates, int target, int startIndex, int sum) {if(sum > target) return; else if(sum == target) {res.push_back(path);return;}for(int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) {if (i > startIndex && candidates[i] == candidates[i-1]) continue;path.push_back(candidates[i]);sum += candidates[i];backtracking(candidates, target, i + 1, sum);sum -= path.back();path.pop_back();}}vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {sort(candidates.begin(), candidates.end());backtracking(candidates, target, 0, 0);return res;}
3.分割回文串
看了题解,本来没什么思路。应该是找出所有字串,然后根据是否回文串剪枝的问题。
这类题要回抽象,怎么把这个问题转换成多叉树我觉得才是关键。
给定一个字符串abccd,二叉树层从当前元素开始选择
a b c c d // 首先从abccd中截取a b c c d
b ccd c cd c d d // 从 bccd 中截取 b ccd
c cd c d // 从 ccd 中截取c cd
c d // 从 cd 中截取c d
d
每一层是不同组合,每一树枝是同一字符串
vector<string> path;vector<vector<string>> res;bool isPalindroom(const string& s, int left, int right) {while(left < right)if(s[left++] != s[right--]) return false;return true;}void backtracking(const string& s, int startIndex) {if(startIndex >= s.size()) {res.push_back(path);return;}for(int i = startIndex; i < s.size(); i++) {if(isPalindroom(s, startIndex, i)) {path.push_back(s.substr(startIndex, i - startIndex + 1));backtracking(s, i + 1);path.pop_back();} }}vector<vector<string>> partition(string s) {backtracking(s, 0);return res;}