1. 程式人生 > >【LeetCode】70. Climbing Stairs

【LeetCode】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?

Note: Given n will be a positive integer.

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

 解題思路:

(1)遞迴解法(此方法在LeetCode中時間超時)

爬上n階臺階有兩種情況:從第n-1階臺階往上爬,或者是從n-2階臺階網上爬。那麼爬上n-1階臺階也有兩種情況:從n-2階臺階往上爬1個臺階,或者是從n-3階臺階往上再爬2階。以此類推。

我們可以寫出遞推公式,f(n)是爬上n階臺階的方法數。

f(1) = 1

f(2)=2

f(n)=f(n-1)+f(n-2)

在寫程式碼的時候,我們可以假設f(0)=1,也就是沒有臺階的時候有1種上法。

public class ClimbingStairs_70 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(climbStairs(4));
	}
	
    public static int climbStairs(int n) {
    	return calcWays(n);
    }
    
    public static int calcWays(int n) {
    	if(n == 0 || n==1) {
    		return 1;
    	}
    	return calcWays(n-1) + calcWays(n-2);
    }

}

(2)記憶化搜素方式:一種優化遞迴解法(此方法可以在LeetCode中AC)

由於遞迴解法重複的計算,我們可以把之前計算過的數值儲存到數組裡面,每次搜素之前n-1的值和n-2的值。

import java.util.Arrays;

public class ClimbingStairs_70 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(climbStairs(4));
	}
	
	public static int[] memo;
    public static int climbStairs(int n) {
    	memo = new int[n+1];
    	Arrays.fill(memo, -1);
    	return calcWays(n);
    }
    
    public static int calcWays(int n) {
    	if(n == 0 || n==1) {
    		return 1;
    	}
    	if(memo[n] == -1) {
    		memo[n] = calcWays(n-1) + calcWays(n-2);
    	}
    	return memo[n];
    }

}

(3)動態規劃解法(此方法可以在LeetCode中AC)


import java.util.Arrays;

public class ClimbingStairs_70 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(climbStairs(4));
	}
	
    public static int climbStairs(int n) {
        int[] memo = new int[n+1];
        Arrays.fill(memo, -1);
        memo[0] = 1;
        memo[1] = 1;
        for(int i=2; i<=n; i++) {
        	if(memo[i] == -1) {
        		memo[i] = memo[i-1] + memo[i-2];
        	}
        }
    	return memo[n];
    }

}