File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed
src/main/java/com/algorithm/study/demo/algorithm/leetcode Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .algorithm .study .demo .algorithm .leetcode ;
2+
3+ /**
4+ * 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
5+ *
6+ * 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
7+ *
8+ * 注意:给定 n 是一个正整数。
9+ *
10+ * 示例 1:
11+ *
12+ * 输入: 2
13+ * 输出: 2
14+ * 解释: 有两种方法可以爬到楼顶。
15+ * 1. 1 阶 + 1 阶
16+ * 2. 2 阶
17+ *
18+ * 来源:力扣(LeetCode)
19+ * 链接:https://leetcode-cn.com/problems/climbing-stairs
20+ */
21+ public class Solution13 {
22+ /**
23+ * 不难发现,这个问题可以被分解为一些包含最优子结构的子问题,即它的最优解可以从其子问题的最优解来有效地构建,我们可以使用动态规划来解决这一问题。
24+ *
25+ * 第 i阶可以由以下两种方法得到:
26+ *
27+ * 在第 (i-1)阶后向上爬 1 阶。
28+ *
29+ * 在第 (i-2)阶后向上爬 2 阶。
30+ *
31+ * 所以到达第 i 阶的方法总数就是到第 (i-1)阶和第 (i-2)阶的方法数之和。
32+ *
33+ * 令 dp[i] 表示能到达第 i 阶的方法总数:
34+ *
35+ * dp[i]=dp[i-1]+dp[i-2]
36+ *
37+ * @param n
38+ * @return
39+ */
40+ public static int climbStairs (int n ) {
41+ if (n <=0 ){
42+ return 0 ;
43+ }
44+ int [] dp =new int [n +1 ];
45+ dp [1 ]=1 ;
46+ dp [2 ]=2 ;
47+ if (n <=2 ){
48+ return dp [n ];
49+ }
50+ for (int i = 3 ; i <=n ; i ++) {
51+ dp [i ]=dp [i -1 ]+dp [i -2 ];
52+ }
53+ return dp [n ];
54+ }
55+
56+ public static void main (String [] args ) {
57+ System .out .println (climbStairs (10 ));
58+ }
59+ }
You can’t perform that action at this time.
0 commit comments