You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
funcclimbStairs(nint) int {
m:=make(map[int]int, n)
returndeep(0, n, m)
}
funcdeep(i, nint, mmap[int]int) int {
ifi>n {
return0
}
ifi==n {
return1
}
ifv, e:=m[i]; e {
returnv
}
m[i] =deep(i+1, n, m) +deep(i+2, n, m)
returnm[i]
}
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例 1:
示例 2:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/climbing-stairs
解答
暴力解法(超时)
每次爬楼梯的时候有两种选择,把这两种选择相加即可
递归 + 字典
上述暴力法其实可以优化的,因为过程中我们会计算多次相同的
deep(i, n)
,那么我们就可以在计算完之后进行保存,如果下次用到了可以直接调用动态规划
其实,到达
m
层的方法,就是到达m-1
层的方法加上到达m-2
层的方法,为什么呢,因为题目给出了一次可以爬一个台阶或者两个台阶,也就是到达m
层的方法,要不是爬了一个台阶,要不就是爬了两个台阶。所以等于m-1 + m-2
种不同的方法。上述代码还有空间优化的可能,因为
dp
这个map有n个元素,其实我们每次都只是用了两个.The text was updated successfully, but these errors were encountered: