Add kotlin code block for array.md and backtracking_algorithm.md. (#1185)

This commit is contained in:
curtishd 2024-03-27 21:47:34 +08:00 committed by GitHub
parent 556af1624c
commit 16350b65e4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 24 additions and 2 deletions

View file

@ -108,7 +108,9 @@
=== "Kotlin"
```kotlin title="array.kt"
/* 初始化数组 */
var arr = IntArray(5) // { 0, 0, 0, 0, 0 }
var nums = intArrayOf(1, 3, 2, 5, 4)
```
=== "Zig"

View file

@ -380,7 +380,27 @@
=== "Kotlin"
```kotlin title=""
/* 回溯算法框架 */
fun backtrack(state: State?, choices: List<Choice?>, res: List<State?>?) {
// 判断是否为解
if (isSolution(state)) {
// 记录解
recordSolution(state, res)
// 不再继续搜索
return
}
// 遍历所有选择
for (choice in choices) {
// 剪枝:判断选择是否合法
if (isValid(state, choice)) {
// 尝试:做出选择,更新状态
makeChoice(state, choice)
backtrack(state, choices, res)
// 回退:撤销选择,恢复到之前的状态
undoChoice(state, choice)
}
}
}
```
=== "Zig"