mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-31 20:37:14 +00:00
Simplify kotlin code and improve code readability (#1198)
* Add kotlin code block for chapter_hashing * Add kotlin code block for chapter_heap. * Add kotlin code block for chapter_stack_and_queue and chapter_tree * fix indentation * Update binary_tree.md * style(kotlin): simplify code and improve readability. * simplify kt code for chapter_computational_complexity. * style(kotlin): replace ArrayList with MutableList. * Update subset_sum_i.kt Use kotlin api instead of java. * Update subset_sum_ii.kt use kotlin api instead of java * style(kotlin): replace ArrayList with mutablelist. --------- Co-authored-by: Yudong Jin <krahets@163.com>
This commit is contained in:
@@ -6,19 +6,17 @@
|
||||
|
||||
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>?>
|
||||
res: MutableList<MutableList<Int>?>
|
||||
) {
|
||||
// 子集和等于 target 时,记录解
|
||||
if (target == 0) {
|
||||
res.add(ArrayList(state))
|
||||
res.add(state.toMutableList())
|
||||
return
|
||||
}
|
||||
// 遍历所有选择
|
||||
@@ -39,11 +37,11 @@ fun backtrack(
|
||||
}
|
||||
|
||||
/* 求解子集和 I */
|
||||
fun subsetSumI(nums: IntArray, target: Int): List<List<Int>?> {
|
||||
val state: MutableList<Int> = ArrayList() // 状态(子集)
|
||||
Arrays.sort(nums) // 对 nums 进行排序
|
||||
fun subsetSumI(nums: IntArray, target: Int): MutableList<MutableList<Int>?> {
|
||||
val state = mutableListOf<Int>() // 状态(子集)
|
||||
nums.sort() // 对 nums 进行排序
|
||||
val start = 0 // 遍历起始点
|
||||
val res: MutableList<List<Int>?> = ArrayList() // 结果列表(子集列表)
|
||||
val res = mutableListOf<MutableList<Int>?>() // 结果列表(子集列表)
|
||||
backtrack(state, target, nums, start, res)
|
||||
return res
|
||||
}
|
||||
@@ -57,4 +55,4 @@ fun main() {
|
||||
|
||||
println("输入数组 nums = ${nums.contentToString()}, target = $target")
|
||||
println("所有和等于 $target 的子集 res = $res")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user