[Leetcode] Climbing Stairs

Posted 言何午

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] Climbing Stairs相关的知识,希望对你有一定的参考价值。

Climbing Stairs 题解

题目来源:https://leetcode.com/problems/climbing-stairs/description/


Description

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

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

Solution


class Solution {
private:
    long long combinatorial(int m, int n) {
        long long res = 1, a = m - n + 1, b = 1;
        long long times = static_cast<long long>(n);
        while (b <= times) {
            res *= a;
            res /= b;
            a++;
            b++;
        }
        return res;
    }
public:
    int climbStairs(int n) {
        int count2 = n / 2;
        long long res = 1;
        for (int i = 1; i <= count2; i++) {
            res += combinatorial(n - i, i);
        }
        return static_cast<int>(res);
    }
};

解题描述

这道题题意是,给出一个数代表台阶数,每次可以上1个或2个台阶,求总共有多少种上台阶的办法。事实上这道题是数学问题,根据不同的上2格台阶的次数,求这些2格台阶所处的位置可用组合数。第一次提交的解法是WA是出现了溢出,所以把与最终计算结果有关的数字类型都改成了long long

以上是关于[Leetcode] Climbing Stairs的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode] Climbing Stairs

LeetCode 70. Climbing Stairs

#LeetCode# 70. Climbing Stairs

Leetcode 70 Climbing Stairs

LeetCode | 0070. Climbing Stairs爬楼梯Python

leetcode 70. Climbing Stairs