- 组合总和
本题是 集合里元素可以用无数次,那么和组合问题的差别 其实仅在于 startIndex上的控制
题目链接/文章讲解:https://programmercarl.com/0039.组合总和.html
视频讲解:https://www.bilibili.com/video/BV1KT4y1M7HJ
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum = function(candidates, target) {
candidates.sort((a,b)=>a-b);
const res = [];
const path = [];
let sum = 0;
let len = candidates.length;
const backtracking = (startIndex) => {
if (sum === target) {
res.push([...path]);
return;
}
for (let i=startIndex;i<len;i++) {
sum += candidates[i];
path.push(candidates[i]);
if (sum > target) {
sum -= candidates[i];
path.pop();
return;
}
backtracking(i);
sum -= candidates[i];
path.pop();
}
}
backtracking(0);
return res;
};
40.组合总和II
本题开始涉及到一个问题了:去重。
注意题目中给我们 集合是有重复元素的,那么求出来的 组合有可能重复,但题目要求不能有重复组合。
题目链接/文章讲解:https://programmercarl.com/0040.组合总和II.html
视频讲解:https://www.bilibili.com/video/BV12V4y1V73A
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum2 = function(candidates, target) {
candidates.sort((a,b)=>a-b);
let len = candidates.length;
const res = [];
const set = new Set();
const path = [];
const backtracking = (startIndex, sum) =>{
if (sum === target) {
res.push([...path]);
return;
}
for (let i=startIndex; i< len;i++) {
if (i>startIndex && candidates[i] === candidates[i-1]) {
continue;
}
let item = candidates[i];
sum += item;
if (sum > target) {
sum -= item;
return;
}
path.push(item);
backtracking(i+1,sum);
path.pop();
sum -= item;
}
}
backtracking(0,0);
return res;
};
131.分割回文串
本题较难,大家先看视频来理解 分割问题,明天还会有一道分割问题,先打打基础。
https://programmercarl.com/0131.分割回文串.html
视频讲解:https://www.bilibili.com/video/BV1c54y1e7k6
function isPalindrome(s, start, end) {
for (let i=start,j=end;i<=end;i++) {
if (s[i]!==s[j]) {
return false;
}
j--;
}
return true;
}
/**
* @param {string} s
* @return {string[][]}
*/
var partition = function(s) {
let res = [];
let path = [];
const backtraversing = (str,startIndex)=>{
if (str.length<=startIndex){
res.push([...path]);
return;
}
for (let i=startIndex;i<str.length;i++) {
if (isPalindrome(str,startIndex,i)) {
path.push(str.slice(startIndex,i+1));
backtraversing(str,i+1);
path.pop();
} else {
continue;
}
}
}
backtraversing(s,0);
return res;
};
标签:return,target,组合,const,sum,随想录,candidates,path,总和
From: https://www.cnblogs.com/yuanyf6/p/18229937