Path Memorizing DFS Java Solution O(n)

  • 0

    The general DFS cause huge run time redundancy. I use a map to memorize the calculated results.

    public class Solution {
        public int climbStairs(int n) {
            // DFS
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            return dfs(n, map);
        private int dfs(int n, Map<Integer, Integer> map){
            // fast ending
            if(map.containsKey(n)) return map.get(n);
            // recursion
            int rslt = dfs(n-1, map) + dfs(n-2, map);
            map.put(n, rslt);
            return rslt;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.