70. 爬楼梯


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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/climbing-stairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.Scanner;

class Solution {

    private static int[][] multiply(int[][] a, int[][] b) {
        int[][] ret = new int[a.length][b[0].length];

        for (int i = 0; i < a.length; ++i) {
            for (int j = 0; j < b[0].length; ++j) {
                for (int k = 0; k < a[0].length; ++k) {
                    ret[i][j] += a[i][k] * b[k][j];
                }
            }
        }

        return ret;
    }

    private static int quickPow(int n) {
        int[][] ret = {
                {2, 1}
        };
        int[][] base = {
                {1, 1},
                {1, 0}
        };

        while (n > 0) {
            if ((n & 1) == 1) {
                ret = multiply(ret, base);
            }
            base = multiply(base, base);
            n >>= 1;
        }

        return ret[0][1];
    }

    public static int climbStairs(int n) {
        if (n <= 0) {
            return 0;
        }


        return quickPow(n - 1);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            System.out.println(climbStairs(in.nextInt()));
        }
    }
}

相关