//02 216.组合总和III
package main
import "fmt"
func combinationSum3(k int, n int) [][]int {
// 全局变量
path := []int{}
res := [][]int{}
// 回溯函数
var backtracking func(targetSum, sum, k, startindex int)
backtracking = func(targetSum, sum, k, startindex int) {
// 终止条件
if sum > targetSum { //和已经大于目标和(剪枝)
return
}
if len(path) == k {
if sum == targetSum {
temp := make([]int, k)
copy(temp, path) //深拷贝结果
res = append(res, temp)
}
return
}
// for循环遍历每个结点,注意剪枝
for i := startindex; i <= 9-(k-len(path))+1; i++ {
sum += i
path = append(path, i)
backtracking(targetSum, sum, k, i+1) //回溯
sum -= i
path = path[:len(path)-1]
}
return
}
backtracking(n, 0, k, 1)
return res
}
func main() {
res := combinationSum3(3, 9)
fmt.Printf("res: %v\n", res) //res: [[1 2 6] [1 3 5] [2 3 4]]
}
//03 17.电话号码的字母组合
package main
import "fmt"
func letterCombinations(digits string) []string {
if digits == string("") { //排除digits为空的情况
return nil
}
//数字字母映射
letterMap := []string{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
// 全局变量
s := []byte{}
res := []string{}
//递归函数
var backtracking func(digits string, index int)
backtracking = func(digits string, index int) {
//终止条件
if index == len(digits) {
temp := string(s)
res = append(res, temp)
return
}
digit := int(digits[index] - '2') //取每一个数字并将它映射为字母
later := letterMap[digit]
//for循环遍历每个结点
for i := 0; i < len(later); i++ {
s = append(s, later[i])
backtracking(digits, index+1) //回溯
s = s[:len(s)-1]
}
return
}
backtracking(digits, 0)
return res
}
func main() {
res := letterCombinations("23")
fmt.Printf("res: %v\n", res) //res: [ad ae af bd be bf cd ce cf]
}