Leetcode 70. 爬楼梯
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] }