mirror of
https://github.com/krahets/hello-algo.git
synced 2026-09-01 20:57:13 +00:00
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
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* File: permutations_i.swift
|
||||
* Created Time: 2023-04-30
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* Алгоритм бэктрекинга: все перестановки I */
|
||||
func backtrack(state: inout [Int], choices: [Int], selected: inout [Bool], res: inout [[Int]]) {
|
||||
// Когда длина состояния равна числу элементов, записать решение
|
||||
if state.count == choices.count {
|
||||
res.append(state)
|
||||
return
|
||||
}
|
||||
// Перебор всех вариантов выбора
|
||||
for (i, choice) in choices.enumerated() {
|
||||
// Отсечение: нельзя выбирать один и тот же элемент повторно
|
||||
if !selected[i] {
|
||||
// Попытка: сделать выбор и обновить состояние
|
||||
selected[i] = true
|
||||
state.append(choice)
|
||||
// Перейти к следующему выбору
|
||||
backtrack(state: &state, choices: choices, selected: &selected, res: &res)
|
||||
// Откат: отменить выбор и восстановить предыдущее состояние
|
||||
selected[i] = false
|
||||
state.removeLast()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Все перестановки I */
|
||||
func permutationsI(nums: [Int]) -> [[Int]] {
|
||||
var state: [Int] = []
|
||||
var selected = Array(repeating: false, count: nums.count)
|
||||
var res: [[Int]] = []
|
||||
backtrack(state: &state, choices: nums, selected: &selected, res: &res)
|
||||
return res
|
||||
}
|
||||
|
||||
@main
|
||||
enum PermutationsI {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
let nums = [1, 2, 3]
|
||||
|
||||
let res = permutationsI(nums: nums)
|
||||
|
||||
print("Входной массив nums = \(nums)")
|
||||
print("Все перестановки res = \(res)")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user