39. 组合总和
要求:给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 **不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
思路
本题允许重复选取,则递归时参数i不需要+1
var combinationSum = function(candidates, target) {
let res = [], path = [], sum = 0
function backstracking(candidates, target, startIndex){
if(sum > target) return
if(sum == target){
res.push([...path])
return
}
for(let i=startIndex; i<candidates.length; i++){
path.push(candidates[i])
sum += candidates[i]
backstracking(candidates, target, i)
path.pop()
sum -= candidates[i]
}
}
backstracking(candidates, target, 0)
return res
};
40. 组合总和 II
要求:给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意: 解集不能包含重复的组合。
思路
本题难点主要在去重,首先要先将数组排序,以便在遍历时判断是否存在与上一个组合相同的搭配,为何 candidates[i] == candidates[i-1],因为如果判断i和i+1那么便会将[1,1,6]这种组合忽略。并且去重时需要判断前一个相同的数是否被使用过,如果不曾使用,那便可直接跳过,不考虑这种可能性。
var combinationSum2 = function(candidates, target) {
candidates.sort()
let res = [], path = [], sum = 0
let used = new Array(candidates.length).fill(0)
function backstracking(candidates, target, startIndex){
if(sum > target) return
if(sum == target){
res.push([...path])
return
}
for(let i=startIndex; i<candidates.length; i++){
if(i>0 && candidates[i] == candidates[i-1] && used[i-1] == 0){
continue
}
path.push(candidates[i])
used[i] = 1
sum += candidates[i]
backstracking(candidates, target, i+1)
used[i] = 0
sum -= candidates[i]
path.pop()
}
}
backstracking(candidates, target, 0)
return res
};
131. 分割回文串
要求:给你一个字符串 s,请你将 **s **分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
思路
var partition = function(s) {
let res = [], path = []
function backstracking(s, index){
if(index == s.length){
res.push([...path])
return
}
for(let i=index; i<s.length; i++){
if(isValid(s, index, i)){
path.push(s.slice(index, i+1))
}else{
continue
}
backstracking(s, i+1)
path.pop()
}
}
function isValid(s, start, end){
for(let i=start, j=end; i<j; i++,j--){
if(s[i] != s[j]){
return false
}
}
return true
}
backstracking(s, 0)
return res
};