//02 216.组合总和III
package mainimport "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 += ipath = append(path, i)backtracking(targetSum, sum, k, i+1) //回溯sum -= ipath = 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 mainimport "fmt"func letterCombinations(digits string) []string {if digits == string("") {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] - '0')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)
}