[代码随想录]Day23-回溯算法part03
题目:39. 组合总和
思路:
一样的递归套路:
- 函数参数:因为要求和,所以有一个当前和的参数;另外因为要保证没有重复的结果,所以后面的遍历不能从头开始,可以加一个index来指定起始位置为当前遍历到的位置,当然也可以直接在传递的切片上动手脚
- 结束条件:因为单个结果没有个数限制,因此只能通过
target <= 0
作为结束条件,只有target == 0
的时候才加入结果;当然这都是建立在切片中没有0的基础上进行的(题目中2 <= candidates[i] <= 40
) - 单层逻辑:从头遍历到尾,先加入,递归退出后再删除(回溯的基本思路)
代码:
var res [][]int
var path []int
func combinationSum(candidates []int, target int) [][]int {
res = make([][]int,0)
path = make([]int, 0, len(candidates))
CombinationSum(candidates, target)
return res
}
func CombinationSum(candidates []int, target int) {
if target <= 0 {
if target == 0 {
res = append(res, append([]int{},path...))
}
return
}
for i := 0; i < len(candidates); i++ {
path = append(path, candidates[i])
CombinationSum(candidates[i:], target - candidates[i])
path = path[:len(path)-1]
}
}
参考:
代码随想录
题目:40. 组合总和 II
思路:
可能出现的一种情况是[1,1,3] target =4,时,会出现两次[1,3]。为了防止出现这种情况,我们要判断是否已经出现过1作为主导的情况,又因为[1,1,3]出现的情况一定包含[1,3],所以放心大胆的删除
代码:
var (
res [][]int
path []int
used []bool
)
func combinationSum2(candidates []int, target int) [][]int {
res = make([][]int, 0)
path = make([]int, 0,len(candidates))
used = make([]bool, len(candidates))
sort.Ints(candidates) //需要进行一个排序
CombinationSum2(candidates, target, 0)
return res
}
func CombinationSum2(candidates []int, target int, index int) {
if target == 0 {
res = append(res, append([]int{},path...))
return
}
for i := index; i < len(candidates); i++ {
if candidates[i] > target {
break
}
if i > 0 && candidates[i] == candidates[i-1] && used[i-1] == false { // 已经有这一层了
continue
}
path = append(path, candidates[i])
used[i] = true
CombinationSum2(candidates, target - candidates[i], i+1)
used[i] = false
path = path[:len(path)-1]
}
}
参考:
代码随想录
题目:131. 分割回文串
思路:
这个题要想清楚遍历的是分割位置而不是某个字符;
结束条件就是字符分割完了
代码:
var (
res [][]string
path []string
)
func partition(s string) [][]string {
res = make([][]string, 0)
path = make([]string, 0, len(s))
Partition(s, 0)
return res
}
func Partition(s string, index int) {
if len(s) == index {
res = append(res, append([]string{},path...))
return
}
for i := index; i < len(s); i++ {
str := s[index:i+1]
if isPartition(str) == true {
path = append(path, str)
Partition(s, i+1)
path = path[:len(path)-1]
}
}
}
func isPartition(s string) bool {
if s == "" {
return false
}
lens := len(s)
for i := 0 ; i < lens / 2; i++ {
if s[i] != s[lens - i - 1] {
return false
}
}
return true
}
参考:
代码随想录