feat(kotlin): Add kotlin code for backtracking chapter (#1088)
* feat(kotlin):new kotlin support files * fix(kotlin): reviewed the formatting, comments and so on. * fix(kotlin): fix the indentation and format * feat(kotlin): Add kotlin code for the backtraking chapter. * fix(kotlin): fix incorrect output of preorder_traversal_iii_template.kt file * fix(kotlin): simplify kotlin codes * fix(kotlin): modify n_queens.kt for consistency.pull/1093/head
parent
e9341c51b5
commit
507357ace1
@ -0,0 +1,53 @@
|
||||
/**
|
||||
* File: permutations_i.kt
|
||||
* Created Time: 2024-01-25
|
||||
* Author: curtishd (1023632660@qq.com)
|
||||
*/
|
||||
|
||||
package chapter_backtracking.permutations_i
|
||||
|
||||
/* 回溯算法:全排列 I */
|
||||
fun backtrack(
|
||||
state: MutableList<Int>,
|
||||
choices: IntArray,
|
||||
selected: BooleanArray,
|
||||
res: MutableList<List<Int>?>
|
||||
) {
|
||||
// 当状态长度等于元素数量时,记录解
|
||||
if (state.size == choices.size) {
|
||||
res.add(ArrayList(state))
|
||||
return
|
||||
}
|
||||
// 遍历所有选择
|
||||
for (i in choices.indices) {
|
||||
val choice = choices[i]
|
||||
// 剪枝:不允许重复选择元素
|
||||
if (!selected[i]) {
|
||||
// 尝试:做出选择,更新状态
|
||||
selected[i] = true
|
||||
state.add(choice)
|
||||
// 进行下一轮选择
|
||||
backtrack(state, choices, selected, res)
|
||||
// 回退:撤销选择,恢复到之前的状态
|
||||
selected[i] = false
|
||||
state.removeAt(state.size - 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 全排列 I */
|
||||
fun permutationsI(nums: IntArray): List<List<Int>?> {
|
||||
val res: MutableList<List<Int>?> = ArrayList()
|
||||
backtrack(ArrayList(), nums, BooleanArray(nums.size), res)
|
||||
return res
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
fun main() {
|
||||
val nums = intArrayOf(1, 2, 3)
|
||||
|
||||
val res = permutationsI(nums)
|
||||
|
||||
println("输入数组 nums = ${nums.contentToString()}")
|
||||
println("所有排列 res = $res")
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
/**
|
||||
* File: permutations_ii.kt
|
||||
* Created Time: 2024-01-25
|
||||
* Author: curtishd (1023632660@qq.com)
|
||||
*/
|
||||
|
||||
package chapter_backtracking.permutations_ii
|
||||
|
||||
/* 回溯算法:全排列 II */
|
||||
fun backtrack(
|
||||
state: MutableList<Int>,
|
||||
choices: IntArray,
|
||||
selected: BooleanArray,
|
||||
res: MutableList<MutableList<Int>?>
|
||||
) {
|
||||
// 当状态长度等于元素数量时,记录解
|
||||
if (state.size == choices.size) {
|
||||
res.add(ArrayList(state))
|
||||
return
|
||||
}
|
||||
// 遍历所有选择
|
||||
val duplicated: MutableSet<Int> = HashSet()
|
||||
for (i in choices.indices) {
|
||||
val choice = choices[i]
|
||||
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
|
||||
if (!selected[i] && !duplicated.contains(choice)) {
|
||||
// 尝试:做出选择,更新状态
|
||||
duplicated.add(choice) // 记录选择过的元素值
|
||||
selected[i] = true
|
||||
state.add(choice)
|
||||
// 进行下一轮选择
|
||||
backtrack(state, choices, selected, res)
|
||||
// 回退:撤销选择,恢复到之前的状态
|
||||
selected[i] = false
|
||||
state.removeAt(state.size - 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 全排列 II */
|
||||
fun permutationsII(nums: IntArray): MutableList<MutableList<Int>?> {
|
||||
val res: MutableList<MutableList<Int>?> = ArrayList()
|
||||
backtrack(ArrayList(), nums, BooleanArray(nums.size), res)
|
||||
return res
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
fun main() {
|
||||
val nums = intArrayOf(1, 2, 2)
|
||||
|
||||
val res = permutationsII(nums)
|
||||
|
||||
println("输入数组 nums = ${nums.contentToString()}")
|
||||
println("所有排列 res = $res")
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
/**
|
||||
* File: preorder_traversal_i_compact.kt
|
||||
* Created Time: 2024-01-25
|
||||
* Author: curtishd (1023632660@qq.com)
|
||||
*/
|
||||
|
||||
package chapter_backtracking.preorder_traversal_i_compact
|
||||
|
||||
import utils.TreeNode
|
||||
import utils.printTree
|
||||
|
||||
var res: MutableList<TreeNode>? = null
|
||||
|
||||
/* 前序遍历:例题一 */
|
||||
fun preOrder(root: TreeNode?) {
|
||||
if (root == null) {
|
||||
return
|
||||
}
|
||||
if (root.value == 7) {
|
||||
// 记录解
|
||||
res!!.add(root)
|
||||
}
|
||||
preOrder(root.left)
|
||||
preOrder(root.right)
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
fun main() {
|
||||
val root = TreeNode.listToTree(mutableListOf(1, 7, 3, 4, 5, 6, 7))
|
||||
println("\n初始化二叉树")
|
||||
printTree(root)
|
||||
|
||||
// 前序遍历
|
||||
res = ArrayList()
|
||||
preOrder(root)
|
||||
|
||||
println("\n输出所有值为 7 的节点")
|
||||
val vals: MutableList<Int> = ArrayList()
|
||||
for (node in res as ArrayList<TreeNode>) {
|
||||
vals.add(node.value)
|
||||
}
|
||||
println(vals)
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: preorder_traversal_ii_compact.kt
|
||||
* Created Time: 2024-01-25
|
||||
* Author: curtishd (1023632660@qq.com)
|
||||
*/
|
||||
|
||||
package chapter_backtracking.preorder_traversal_ii_compact
|
||||
|
||||
import utils.TreeNode
|
||||
import utils.printTree
|
||||
|
||||
var path: MutableList<TreeNode>? = null
|
||||
var res: MutableList<List<TreeNode>>? = null
|
||||
|
||||
/* 前序遍历:例题二 */
|
||||
fun preOrder(root: TreeNode?) {
|
||||
if (root == null) {
|
||||
return
|
||||
}
|
||||
// 尝试
|
||||
path!!.add(root)
|
||||
if (root.value == 7) {
|
||||
// 记录解
|
||||
res!!.add(ArrayList(path!!))
|
||||
}
|
||||
preOrder(root.left)
|
||||
preOrder(root.right)
|
||||
// 回退
|
||||
path!!.removeAt(path!!.size - 1)
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
fun main() {
|
||||
val root = TreeNode.listToTree(mutableListOf(1, 7, 3, 4, 5, 6, 7))
|
||||
println("\n初始化二叉树")
|
||||
printTree(root)
|
||||
|
||||
// 前序遍历
|
||||
path = java.util.ArrayList<TreeNode>()
|
||||
res = java.util.ArrayList<List<TreeNode>>()
|
||||
preOrder(root)
|
||||
|
||||
println("\n输出所有根节点到节点 7 的路径")
|
||||
for (path in res as ArrayList<List<TreeNode>>) {
|
||||
val values: MutableList<Int> = ArrayList()
|
||||
for (node in path) {
|
||||
values.add(node.value)
|
||||
}
|
||||
println(values)
|
||||
}
|
||||
}
|
@ -0,0 +1,52 @@
|
||||
/**
|
||||
* File: preorder_traversal_iii_compact.kt
|
||||
* Created Time: 2024-01-25
|
||||
* Author: curtishd (1023632660@qq.com)
|
||||
*/
|
||||
|
||||
package chapter_backtracking.preorder_traversal_iii_compact
|
||||
|
||||
import utils.TreeNode
|
||||
import utils.printTree
|
||||
|
||||
var path: MutableList<TreeNode>? = null
|
||||
var res: MutableList<List<TreeNode>>? = null
|
||||
|
||||
/* 前序遍历:例题三 */
|
||||
fun preOrder(root: TreeNode?) {
|
||||
// 剪枝
|
||||
if (root == null || root.value == 3) {
|
||||
return
|
||||
}
|
||||
// 尝试
|
||||
path!!.add(root)
|
||||
if (root.value == 7) {
|
||||
// 记录解
|
||||
res!!.add(ArrayList(path!!))
|
||||
}
|
||||
preOrder(root.left)
|
||||
preOrder(root.right)
|
||||
// 回退
|
||||
path!!.removeAt(path!!.size - 1)
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
fun main() {
|
||||
val root = TreeNode.listToTree(mutableListOf(1, 7, 3, 4, 5, 6, 7))
|
||||
println("\n初始化二叉树")
|
||||
printTree(root)
|
||||
|
||||
// 前序遍历
|
||||
path = ArrayList()
|
||||
res = ArrayList()
|
||||
preOrder(root)
|
||||
|
||||
println("\n输出所有根节点到节点 7 的路径,路径中不包含值为 3 的节点")
|
||||
for (path in res as ArrayList<List<TreeNode>>) {
|
||||
val values: MutableList<Int> = ArrayList()
|
||||
for (node in path) {
|
||||
values.add(node.value)
|
||||
}
|
||||
println(values)
|
||||
}
|
||||
}
|
@ -0,0 +1,83 @@
|
||||
/**
|
||||
* File: preorder_traversal_iii_template.kt
|
||||
* Created Time: 2024-01-25
|
||||
* Author: curtishd (1023632660@qq.com)
|
||||
*/
|
||||
|
||||
package chapter_backtracking.preorder_traversal_iii_template
|
||||
|
||||
import utils.TreeNode
|
||||
import utils.printTree
|
||||
import java.util.*
|
||||
|
||||
/* 判断当前状态是否为解 */
|
||||
fun isSolution(state: List<TreeNode?>): Boolean {
|
||||
return state.isNotEmpty() && state[state.size - 1]?.value == 7
|
||||
}
|
||||
|
||||
/* 记录解 */
|
||||
fun recordSolution(state: MutableList<TreeNode?>?, res: MutableList<List<TreeNode?>?>) {
|
||||
res.add(state?.let { ArrayList(it) })
|
||||
}
|
||||
|
||||
/* 判断在当前状态下,该选择是否合法 */
|
||||
fun isValid(state: List<TreeNode?>?, choice: TreeNode?): Boolean {
|
||||
return choice != null && choice.value != 3
|
||||
}
|
||||
|
||||
/* 更新状态 */
|
||||
fun makeChoice(state: MutableList<TreeNode?>, choice: TreeNode?) {
|
||||
state.add(choice)
|
||||
}
|
||||
|
||||
/* 恢复状态 */
|
||||
fun undoChoice(state: MutableList<TreeNode?>, choice: TreeNode?) {
|
||||
state.removeLast()
|
||||
}
|
||||
|
||||
/* 回溯算法:例题三 */
|
||||
fun backtrack(
|
||||
state: MutableList<TreeNode?>,
|
||||
choices: List<TreeNode?>,
|
||||
res: MutableList<List<TreeNode?>?>
|
||||
) {
|
||||
// 检查是否为解
|
||||
if (isSolution(state)) {
|
||||
// 记录解
|
||||
recordSolution(state, res)
|
||||
}
|
||||
// 遍历所有选择
|
||||
for (choice in choices) {
|
||||
// 剪枝:检查选择是否合法
|
||||
if (isValid(state, choice)) {
|
||||
// 尝试:做出选择,更新状态
|
||||
makeChoice(state, choice)
|
||||
// 进行下一轮选择
|
||||
backtrack(state, listOf(choice!!.left, choice.right), res)
|
||||
// 回退:撤销选择,恢复到之前的状态
|
||||
undoChoice(state, choice)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
fun main() {
|
||||
val root = TreeNode.listToTree(mutableListOf(1, 7, 3, 4, 5, 6, 7))
|
||||
println("\n初始化二叉树")
|
||||
printTree(root)
|
||||
|
||||
// 回溯算法
|
||||
val res: MutableList<List<TreeNode?>?> = ArrayList()
|
||||
backtrack(ArrayList(), mutableListOf(root), res)
|
||||
|
||||
println("\n输出所有根节点到节点 7 的路径,要求路径中不包含值为 3 的节点")
|
||||
for (path in res) {
|
||||
val vals = ArrayList<Int>()
|
||||
for (node in path!!) {
|
||||
if (node != null) {
|
||||
vals.add(node.value)
|
||||
}
|
||||
}
|
||||
println(vals)
|
||||
}
|
||||
}
|
@ -0,0 +1,60 @@
|
||||
/**
|
||||
* File: subset_sum_i.kt
|
||||
* Created Time: 2024-01-25
|
||||
* Author: curtishd (1023632660@qq.com)
|
||||
*/
|
||||
|
||||
package chapter_backtracking.subset_sum_i
|
||||
|
||||
import java.util.*
|
||||
|
||||
/* 回溯算法:子集和 I */
|
||||
fun backtrack(
|
||||
state: MutableList<Int>,
|
||||
target: Int,
|
||||
choices: IntArray,
|
||||
start: Int,
|
||||
res: MutableList<List<Int>?>
|
||||
) {
|
||||
// 子集和等于 target 时,记录解
|
||||
if (target == 0) {
|
||||
res.add(ArrayList(state))
|
||||
return
|
||||
}
|
||||
// 遍历所有选择
|
||||
// 剪枝二:从 start 开始遍历,避免生成重复子集
|
||||
for (i in start..<choices.size) {
|
||||
// 剪枝一:若子集和超过 target ,则直接结束循环
|
||||
// 这是因为数组已排序,后边元素更大,子集和一定超过 target
|
||||
if (target - choices[i] < 0) {
|
||||
break
|
||||
}
|
||||
// 尝试:做出选择,更新 target, start
|
||||
state.add(choices[i])
|
||||
// 进行下一轮选择
|
||||
backtrack(state, target - choices[i], choices, i, res)
|
||||
// 回退:撤销选择,恢复到之前的状态
|
||||
state.removeAt(state.size - 1)
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解子集和 I */
|
||||
fun subsetSumI(nums: IntArray, target: Int): List<List<Int>?> {
|
||||
val state: MutableList<Int> = ArrayList() // 状态(子集)
|
||||
Arrays.sort(nums) // 对 nums 进行排序
|
||||
val start = 0 // 遍历起始点
|
||||
val res: MutableList<List<Int>?> = ArrayList() // 结果列表(子集列表)
|
||||
backtrack(state, target, nums, start, res)
|
||||
return res
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
fun main() {
|
||||
val nums = intArrayOf(3, 4, 5)
|
||||
val target = 9
|
||||
|
||||
val res = subsetSumI(nums, target)
|
||||
|
||||
println("输入数组 nums = ${nums.contentToString()}, target = $target")
|
||||
println("所有和等于 $target 的子集 res = $res")
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
/**
|
||||
* File: subset_sum_ii.kt
|
||||
* Created Time: 2024-01-25
|
||||
* Author: curtishd (1023632660@qq.com)
|
||||
*/
|
||||
|
||||
package chapter_backtracking.subset_sum_ii
|
||||
|
||||
import java.util.*
|
||||
|
||||
/* 回溯算法:子集和 II */
|
||||
fun backtrack(
|
||||
state: MutableList<Int>,
|
||||
target: Int,
|
||||
choices: IntArray,
|
||||
start: Int,
|
||||
res: MutableList<List<Int>?>
|
||||
) {
|
||||
// 子集和等于 target 时,记录解
|
||||
if (target == 0) {
|
||||
res.add(ArrayList(state))
|
||||
return
|
||||
}
|
||||
// 遍历所有选择
|
||||
// 剪枝二:从 start 开始遍历,避免生成重复子集
|
||||
// 剪枝三:从 start 开始遍历,避免重复选择同一元素
|
||||
for (i in start..<choices.size) {
|
||||
// 剪枝一:若子集和超过 target ,则直接结束循环
|
||||
// 这是因为数组已排序,后边元素更大,子集和一定超过 target
|
||||
if (target - choices[i] < 0) {
|
||||
break
|
||||
}
|
||||
// 剪枝四:如果该元素与左边元素相等,说明该搜索分支重复,直接跳过
|
||||
if (i > start && choices[i] == choices[i - 1]) {
|
||||
continue
|
||||
}
|
||||
// 尝试:做出选择,更新 target, start
|
||||
state.add(choices[i])
|
||||
// 进行下一轮选择
|
||||
backtrack(state, target - choices[i], choices, i + 1, res)
|
||||
// 回退:撤销选择,恢复到之前的状态
|
||||
state.removeAt(state.size - 1)
|
||||
}
|
||||
}
|
||||
|
||||
/* 求解子集和 II */
|
||||
fun subsetSumII(nums: IntArray, target: Int): List<List<Int>?> {
|
||||
val state: MutableList<Int> = ArrayList() // 状态(子集)
|
||||
Arrays.sort(nums) // 对 nums 进行排序
|
||||
val start = 0 // 遍历起始点
|
||||
val res: MutableList<List<Int>?> = ArrayList() // 结果列表(子集列表)
|
||||
backtrack(state, target, nums, start, res)
|
||||
return res
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
fun main() {
|
||||
val nums = intArrayOf(4, 4, 5)
|
||||
val target = 9
|
||||
|
||||
val res = subsetSumII(nums, target)
|
||||
|
||||
println("输入数组 nums = ${nums.contentToString()}, target = $target")
|
||||
println("所有和等于 $target 的子集 res = $res")
|
||||
}
|
Loading…
Reference in new issue