Leetcode 70. 爬樓梯
阿新 • • 發佈:2022-04-22
70. 爬樓梯 - 力扣(LeetCode) (leetcode-cn.com)
思路
動態規劃:
【轉載】動態規劃五部曲: 1.確定dp[i]的下標以及dp值的含義: 爬到第i層樓梯,有dp[i]種方法; 2.確定動態規劃的遞推公式:dp[i] = dp[i-1] + dp[i-2]; 3.dp陣列的初始化:因為提示中,1<=n<=45 所以初始化值,dp[1] = 1, dp[2] = 2; 4.確定遍歷順序:分析遞推公式可知當前值依賴前兩個值來確定,所以遞推順序應該是從前往後; 5.列印dp陣列看自己寫的對不對;
滾動陣列:
func climbStairs(n int) int { if n==1{ return 1 } if n==2{ return 2 } one:=1 two:=2 three:=0 for i:=3;i<=n;i++{ three=one+two one,two=two,three } return three }
func climbStairs(n int) int { if n<=1{ return 1 } dp:=make(map[int]int,0) dp[1]=1 dp[2]=2 for i:=3;i<=n;i++{ dp[i]=dp[i-1]+dp[i-2] } return dp[n] }