加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

70. 爬楼梯

发布时间:2020-12-14 04:22:15 所属栏目:大数据 来源:网络整理
导读:You are climbing a stair case. It takes? n ?steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note:?Given? n ?will be a positive integer. Example 1: Input: 2Output:

You are climbing a stair case. It takes?n?steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note:?Given?n?will be a positive integer.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

假设你正在爬楼梯。需要?n?阶你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

注意:给定?n?是一个正整数。

示例 1:

输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1.  1 阶 + 1 阶
2.  2 阶

示例 2:

输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1.  1 阶 + 1 阶 + 1 阶
2.  1 阶 + 2 阶
3.  2 阶 + 1 阶

 1 class Solution {
 2     func climbStairs(_ n: Int) -> Int {
 3         //动态规划
 4         //把运算的结果保存下来
 5         //下一次运算时直接调用
 6         if n==1 || n==2 {return n}
 7         //创建一个特定大小的数组
 8         //并将其所有值设置为相同的默认值
 9         var arr:[Int] = Array(repeating: 0,count: n+1)
10         //斐波那契数列
11         //递归方式会时很多运算时重复,导致运算时间超时
12         arr[1] = 1
13         arr[2] = 2
14         for i in 3...n
15         {
16             arr[i] =  arr[i-1] + arr[i-2]
17         }
18         return arr[n] 
19     }
20 }


不需要用数组存下所有的数据:8ms

 1 class Solution {
 2     func climbStairs(_ n: Int) -> Int {
 3         if n < 3 {
 4             return n
 5         }
 6         
 7         var a = 1
 8         var b = 2
 9         var res = 0
10         
11         for _ in 2..<n {
12             res = a + b
13             a = b
14             b = res
15         }
16         
17         return res
18     }
19 }

?


版本:12ms(与法1只存储方式不同)

class Solution {
    func climbStairs(_ n: Int) -> Int 
    {
    guard n != 1 else { return 1 }

    var stairCount = [Int]()
    stairCount.insert(0,at: 0)
    stairCount.insert(1,at: 1)
    stairCount.insert(2,at: 2)
    if n > 2 
        {
            for i in 3...n 
            {
                stairCount.append(stairCount[i - 1] + stairCount[i - 2])
            }
        }
        return stairCount[n]
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读