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.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
/* *
* F i l e : c l i m b i n g _ s t a i r s _ d p . s w i f t
* C r e a t e d T i m e : 2 0 2 3 - 0 7 - 1 5
* A u t h o r : n u o m i 1 ( n u o m i 1 @ q q . c o m )
*/
/* 爬 楼 梯 : 动 态 规 划 */
func climbingStairsDP ( n : Int ) -> Int {
if n = = 1 || n = = 2 {
return n
}
// 初 始 化 d p 表 , 用 于 存 储 子 问 题 的 解
var dp = Array ( repeating : 0 , count : n + 1 )
// 初 始 状 态 : 预 设 最 小 子 问 题 的 解
dp [ 1 ] = 1
dp [ 2 ] = 2
// 状 态 转 移 : 从 较 小 子 问 题 逐 步 求 解 较 大 子 问 题
for i in stride ( from : 3 , through : n , by : 1 ) {
dp [ i ] = dp [ i - 1 ] + dp [ i - 2 ]
}
return dp [ n ]
}
/* 爬 楼 梯 : 空 间 优 化 后 的 动 态 规 划 */
func climbingStairsDPComp ( n : Int ) -> Int {
if n = = 1 || n = = 2 {
return n
}
var a = 1
var b = 2
for _ in stride ( from : 3 , through : n , by : 1 ) {
( a , b ) = ( b , a + b )
}
return b
}
@ main
enum ClimbingStairsDP {
/* D r i v e r C o d e */
static func main ( ) {
let n = 9
var res = climbingStairsDP ( n : n )
print ( " 爬 \( n ) 阶楼梯共有 \( res ) 种方案 " )
res = climbingStairsDPComp ( n : n )
print ( " 爬 \( n ) 阶楼梯共有 \( res ) 种方案 " )
}
}