算法记录Day 26 | 回溯算法part03

40 阅读1分钟

算法记录Day 26 | 回溯算法part03

LeetCode 39. 组合总和

题目链接:39. 组合总和

题解
func combinationSum(candidates []int, target int) [][]int {
	result := make([][]int, 0)
	dfs39(candidates, 0, target, 0, []int{}, &result)
	return result
}

func dfs39(candidates []int, start int, target int, sum int, path []int, result *[][]int) {
	if sum > target {
		return
	}
	if sum == target {
		temp := make([]int, len(path))
		copy(temp, path)
		*result = append(*result, temp)
		return
	}
	for i := start; i < len(candidates); i++ {
		path = append(path, candidates[i])
		sum += candidates[i]
		dfs39(candidates, i, target, sum, path, result)
		path = path[:len(path)-1]
		sum -= candidates[i]
	}
}

LeetCode 40.组合总和II

题目链接:40. 组合总和 II

题解
import "sort"

func combinationSum2(candidates []int, target int) [][]int {
	result := make([][]int, 0)
	used := make([]bool, len(candidates))
	sort.Ints(candidates)
	dfs40(candidates, 0, target, 0, used, []int{}, &result)
	return result
}

func dfs40(candidates []int, start int, target int, sum int, used []bool, path []int, result *[][]int) {
	if sum == target {
		temp := make([]int, len(path))
		copy(temp, path)
		*result = append(*result, temp)
		return
	}
	for i := start; i < len(candidates); i++ {
		if sum+candidates[i] > target {
			break
		}
		if i > 0 && candidates[i] == candidates[i-1] && !used[i-1] {
			continue
		}
		sum += candidates[i]
		path = append(path, candidates[i])
		used[i] = true
		dfs40(candidates, i+1, target, sum, used, path, result)
		sum -= candidates[i]
		path = path[:len(path)-1]
		used[i] = false
	}
}

LeetCode 131.分割回文串

题目链接:131. 分割回文串

题解
func partition(s string) [][]string {
	result := make([][]string, 0)
	dfs131(s, 0, []string{}, &result)
	return result
}

func dfs131(s string, start int, path []string, result *[][]string) {
	if start == len(s) {
		temp := make([]string, len(path))
		copy(temp, path)
		*result = append(*result, temp)
		return
	}
	for i := start; i < len(s); i++ {
		if isPair(s, start, i) {
			path = append(path, s[start:i+1])
			dfs131(s, i+1, path, result)
			path = path[:len(path)-1]
		}
	}
}

func isPair(s string, start int, end int) bool {
	for start < end {
		if s[start] != s[end] {
			return false
		}
		start++
		end--
	}
	return true
}