Files
hello-algo/ru/codes/kotlin/chapter_backtracking/permutations_i.kt
Yudong Jin 772183705e Add ru version (#1865)
* Add Russian docs site baseline

* Add Russian localized codebase

* Polish Russian code wording

* Update ru code translation.

* Update code translation and chapter covers.

* Fix pythontutor extraction.

* Add README and landing page.

* placeholder of profiles

* Use figures of English version

* Remove chapter paperbook
2026-03-28 04:24:07 +08:00

53 lines
1.8 KiB
Kotlin
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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<MutableList<Int>?>
) {
// Когда длина состояния равна числу элементов, записать решение
if (state.size == choices.size) {
res.add(state.toMutableList())
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): MutableList<MutableList<Int>?> {
val res = mutableListOf<MutableList<Int>?>()
backtrack(mutableListOf(), 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")
}