[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

原文地址:https://www.cnblogs.com/yanhewu/p/8371692.html