天天看點

Leetcode70. 爬樓梯

題目傳送位址: ​​https://leetcode.cn/problems/climbing-stairs/​​

運作效率:

Leetcode70. 爬樓梯
public static int climbStairs(int n) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int i = climbStairsWithMap(n, map);
        return i;
    }
//用map可以提升查詢性能,加快查詢速度
    public static int climbStairsWithMap(int n, HashMap<Integer,Integer> map){
        if(map.containsKey(n)){
            return map.get(n);
        }
        //處理邊界條件
        if(n==1){
            return 1;
        }
        if(n==2){
            return 2;
        }
        //要爬到第n階,可以有2種辦法,第一種是從n-1階跳一格到n階     第二種是從n-2階跳2格到n階
        int i = climbStairsWithMap(n - 1, map) + climbStairsWithMap(n - 2, map);
        map.put(n,i);
        return i;
    }