You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/codes/swift/chapter_dynamic_programming/climbing_stairs_backtrack.s...

45 lines
1.1 KiB

/**
* File: climbing_stairs_backtrack.swift
* Created Time: 2023-07-15
* Author: nuomi1 (nuomi1@qq.com)
*/
/* */
func backtrack(choices: [Int], state: Int, n: Int, res: inout [Int]) {
// n 1
if state == n {
res[0] += 1
}
//
for choice in choices {
// n
if state + choice > n {
continue
}
//
backtrack(choices: choices, state: state + choice, n: n, res: &res)
// 退
}
}
/* */
func climbingStairsBacktrack(n: Int) -> Int {
let choices = [1, 2] // 1 2
let state = 0 // 0
var res: [Int] = []
res.append(0) // 使 res[0]
backtrack(choices: choices, state: state, n: n, res: &res)
return res[0]
}
@main
enum ClimbingStairsBacktrack {
/* Driver Code */
static func main() {
let n = 9
let res = climbingStairsBacktrack(n: n)
print("\(n) 阶楼梯共有 \(res) 种方案")
}
}