LeetCode 70th title

Title Description

Suppose you are climbing stairs. N order you need to get to the roof.

Every time you can climb one or two steps. How many different ways can climb to the roof of it?

Note: Given n is a positive integer.

A Solution

Recursively solving violent no brain, the time complexity (O (2 ^ n))

public int climbStairs(int n) {
    return climb_Stairs(0,n);
}
public int climb_Stairs(int i,int n){
    if(i > n)    return 0;
    if(i == n)  return 1;
    return climb_Stairs(i+1,n) + climb_Stairs(i+2,n);
}

Solution two

Optimized version of a solution, increasing the intermediate results of a cache array when called again and then return the result. Time complexity of O (n)
and some thinking about this question is how specific memory store intermediate data, how to return, after these reflections supplement (recursively paper should be run with the brain and brain cells procedures and most waste paper or too dishes.)

public int climbStairs(int n) {
    int[] memo = new int[n + 1];
    return climb_Stairs(0,n,memo);
}
public int climb_Stairs(int i,int n,int[] memo){
    if(i > n)    return 0;
    if(i == n)  return 1;
    if(memo[i] > 0) {
        //System.out.println("如果memo[ "+ i + " ]>0   "+Arrays.toString(memo));
        return memo[i];
    }
    //System.out.println(i+"--  --"+Arrays.toString(memo));
    memo[i] = climb_Stairs(i+1,n,memo) + climb_Stairs(i+2,n,memo);
    //System.out.println(i+"--------------------"+Arrays.toString(memo));
    return memo[i];
}

Solution three

Write recursive when you can find the middle value is generated Fibonacci numbers, so:

public int climbStairs(int n) {
	if (n <= 2)  return n;
	int f1 = 1,f2 = 2,f3 = 3;
	for(int i = 3; i < n + 1; i++) {
		f3 = f1 + f2;
		f1 = f2;
		f2 = f3;
	}
	return f3;
}
Released five original articles · won praise 0 · Views 41

Guess you like

Origin blog.csdn.net/weixin_42610002/article/details/104062303