70.Climbing Stairs

Posted cznczai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了70.Climbing Stairs相关的知识,希望对你有一定的参考价值。

技术图片
递归解决方法

public class Main 
    int sum = 0;
 
    public int climbStairs(int n) 
        if (n <= 0) //
            sum++;
 
         else if (n == 1) 
            sum++;
         else 
            climbStairs(n - 1);//每一种结果都有两种选择 要么一步 要么两步
            climbStairs(n - 2);
        
 
        return sum;
    
    public static void main(String[]args) 
        Main m=new Main();
        System.out.println(m.climbStairs(2));
    

非递归

public class Main 
    int sum = 0;
 
    public int climbStairs(int n) 
        if (n <= 1) 
            return 1;
         else 
            int[] arr = new int[n];
            arr[0] = 1;
            arr[1] = 2;
            int i = 2;
            while (i < n && i>= 2) 
                arr[i ] = arr[i-1] + arr[i - 2];//每一个都是前两位之和 
                i++;
                
            
            return arr[n - 1];
        
    
 
    public static void main(String[] args) 
        Main m = new Main();
        System.out.println(m.climbStairs(8));
    

其他人解法也是大同小异

private int[] memo;
 
public int climbStairs(int n) 
    memo = new int[n + 1];
    Arrays.fill(memo, -1);
    return getClimbStairs(n);

 
private int getClimbStairs(int n) 
    if (n == 1) 
        return 1;
    
 
    if (n == 2) 
        return 2;
    
 
    if (memo[n] == -1) 
        memo[n] = getClimbStairs(n - 1) + getClimbStairs(n - 2);
    
    return memo[n];

int climbStairs(int n)
 
int x1=0,x2=1;
int i;
int sum;
for(i=1;i<=n;i++)

    sum=x1+x2;
    x1=x2;
    x2=sum;

return sum;

哈希表 有趣

public class Solution 
 
int result;
HashMap<Integer, Integer> memo = new HashMap<Integer, Integer>();
 
public int climbStairs(int n) 
    if(n < 2) 
        return 1;
    
    if(memo.containsKey(n)) 
        return memo.get(n);
    
    result = climbStairs(n-1) + climbStairs(n-2);
    memo.put(n,result);
    return result;

以上是关于70.Climbing Stairs的主要内容,如果未能解决你的问题,请参考以下文章

70. Climbing Stairs

70. Climbing Stairs

70. Climbing Stairs

LeetCode 70. Climbing Stairs

#LeetCode# 70. Climbing Stairs

leetcode 70. Climbing Stairs