编程语言
首页 > 编程语言> > DFS/回溯算法

DFS/回溯算法

作者:互联网

回溯算法模板:

result = []
def backtrack(路径, 选择列表):
 if 满⾜结束条件:
 result.add(路径)
 return
 for 选择 in 选择列表:
 做选择
 backtrack(路径, 选择列表)
 撤销选择

  

力扣46题

func permute(nums []int) [][]int {
	ans := make([][]int, 0)
	track := make([]int, 0)
	visited := map[int]bool{}
	sort.Ints(nums)

	var backtrack func()
	backtrack = func() {
		if len(track) == len(nums) {
			ans = append(ans, append([]int{}, track...))
			return
		}
		for i := 0; i < len(nums); i++ {
			if visited[i] {
				continue
			}
			visited[i] = true
			track = append(track, nums[i])
			backtrack()
			visited[i] = false
			track = track[:len(track)-1]
		}
	}
	backtrack()
	return ans
}

  

标签:backtrack,track,nums,DFS,int,算法,ans,len,回溯
来源: https://www.cnblogs.com/mango1997/p/16103705.html