70. Climbing Stairs

题目:

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?

链接: http://leetcode.com/problems/climbing-stairs/

题解:

费波纳茨序列,使用Dynamic Programming,先构建一个一维数组。Time Complexity - O(n), Space Complexity - O(n)。

public class Solution {

    public int climbStairs(int n) {

        int[] result = new int[n + 1];

        result[0] = 1;

        result[1] = 1;
for(int i = 2; i < n + 1; i ++){ result[i] = result[i - 1] + result[i - 2]; }
return result[n]; } }

 

可以继续优化空间复杂度,使用两个变量存储之前的值。 Time Complexity - O(n), Space Complexity - O(1)

public class Solution {

    public int climbStairs(int n) {

        int result = 1, prevStep = 1, curStep = 1;

        

        for(int i = 2; i < n + 1; i ++){

            result = prevStep + curStep;

            prevStep = curStep;

            curStep = result;

        }

        

        return result;

    }

}

 

还可以继续优化 - 使用矩阵法计算Fib。 Time Complexity - O(logn),Space Complexity - O(1).

http://www.gocalf.com/blog/calc-fibonacci.html 

测试:

你可能感兴趣的:(bing)