1. 程式人生 > >[Leetcode] Climbing Stairs

[Leetcode] Climbing Stairs

problem cli ati bin not href 可用 ger 數學問題

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