hello-algo/codes/swift/chapter_dynamic_programming/climbing_stairs_backtrack.swift
nuomi1 9ea8a73059
Feature/chapter dynamic programming swift (#608)
* feat: add Swift codes for intro_to_dynamic_programming article

* feat: add Swift codes for dp_problem_features article

* feat: add Swift codes for dp_solution_pipeline article

* feat: add Swift codes for knapsack_problem article

* feat: add Swift codes for unbounded_knapsack_problem article

* feat: add Swift codes for edit_distance_problem article
2023-07-18 12:49:03 +08:00

42 lines
1.1 KiB
Swift
Raw 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: 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 {
break
}
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) 种方案")
}
}