皇后问题 多路递归 回溯
线程 栈帧链
多处理器编程:从入门到放弃 (线程库;现代处理器和宽松内存模型) [南京大学2022操作系统-P3]_哔哩哔哩_bilibili https://www.bilibili.com/video/BV13u411X72Q/?spm_id_from=333.788
程序=状态机
操作系统上的程序 (什么是程序和编译器) [南京大学2022操作系统-P2]_哔哩哔哩_bilibili https://www.bilibili.com/video/BV12L4y1379V
递归: 函数的一个有一个状态
多路递归
https://leetcode.cn/problems/combination- dfs/solution/zu-he-zong-he-by-leetcode-solution/
Palindrome Partitioning - LeetCode https://leetcode.com/problems/palindrome-partitioning/
Types of Recursions - GeeksforGeeks https://www.geeksforgeeks.org/types-of-recursions/
递归分类
bug
import ( "log" "strings" ) func solveNQueens(n int) [][]string { ans := [][]string{} currentPoints := [][]int{} ok := func(x, y int) bool { m := len(currentPoints) for i := 0; i < m; i++ { p := currentPoints[i] r, c := p[0], p[1] if x == r || y == c || x-r == y-c || x-r == c-y { return false } } return true } oneAns := func() []string { one := []string{} for _, v := range currentPoints { a := []string{} c := v[1] for y := 0; y < n; y++ { s := "." if y == c { s = "Q" } a = append(a, s) } one = append(one, strings.Join(a, "")) } return one } var backtrack func(x int) backtrack = func(x int) { for y := 0; y < n; y++ { if x == 0 { currentPoints = [][]int{} } log.Print(x, " ", y, " ", currentPoints) if ok(x, y) { currentPoints = append(currentPoints, []int{x, y}) log.Print("OK", currentPoints) if len(currentPoints) == n { log.Print("OK-n", n, currentPoints) ans = append(ans, oneAns()) return } backtrack(x + 1) currentPoints = currentPoints[0 : len(currentPoints)-1] } } } backtrack(0) log.Print(ans) return ans } /* 51. N 皇后 - 力扣(LeetCode) https://leetcode.cn/problems/n-queens/ */
import ( "reflect" "testing" ) func Test_solveNQueens(t *testing.T) { type args struct { n int } tests := []struct { name string args args want [][]string }{ // TODO: Add test cases. // {name: "1", args: args{n: 1}, want: [][]string{{"Q"}}}, // {name: "4", args: args{n: 4}, want: [][]string{{".Q..", "...Q", "Q...", "..Q."}, {"..Q.", "Q...", "...Q", ".Q.."}}}, {name: "5", args: args{n: 5}, want: [][]string{{"Q....", "..Q..", "....Q", ".Q...", "...Q."}, {"Q....", "...Q.", ".Q...", "....Q", "..Q.."}, {".Q...", "...Q.", "Q....", "..Q..", "....Q"}, {".Q...", "....Q", "..Q..", "Q....", "...Q."}, {"..Q..", "Q....", "...Q.", ".Q...", "....Q"}, {"..Q..", "....Q", ".Q...", "...Q.", "Q...."}, {"...Q.", "Q....", "..Q..", "....Q", ".Q..."}, {"...Q.", ".Q...", "....Q", "..Q..", "Q...."}, {"....Q", ".Q...", "...Q.", "Q....", "..Q.."}, {"....Q", "..Q..", "Q....", "...Q.", ".Q..."}}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := solveNQueens(tt.args.n); !reflect.DeepEqual(got, tt.want) { t.Errorf("solveNQueens() = %v, want %v", got, tt.want) } }) } }
少一行代码