// 无重复数组的全排列
func FullArray(nums []int) [][]int {
var res [][]int
var path []int
var in func()
n := len(nums)
// 用于记录元素是否被取用过
used := make(map[int]bool)
in = func(){
if len(path) == n {
tmp := make([]int, n)
copy(tmp, path)
res = append(res, tmp)
return
}
for i := 0; i < n; i++ {
if used[nums[i]] {
continue
}
used[nums[i]] = true
path = append(path, nums[i])
in()
used[nums[i]] = false
path = path[:len(path)-1]
}
}
in()
return res
}
拆分单词
回溯算法,按照回溯算法模板处理
// 拆分字符串
func WordBreak(s string, wordDict []string) bool {
n := len(s)
var in func(startIndex int) bool
memory := make(map[int]bool)
in = func(startIndex int) bool {
// 回溯终止条件
if startIndex >= n {
return true
}
// 记录,减少循环遍历次数
if _, ok := memory[startIndex]; ok && !memory[startIndex] {
return memory[startIndex]
}
for i := startIndex; i < n; i++ {
tmp := i + 1
word := s[startIndex:tmp]
//fmt.Printf("word is %v\n", word)
if wordDictHas(word, wordDict) && in(i+1) {
return true
}
}
memory[startIndex] = false
return false
}
return in(0)
}
func wordDictHas(word string, wordDict []string) bool {
for _, v := range wordDict {
if word == v {
return true
}
}
return false
}