Advertisement
gelita

climb stairs dynamic programming with tabulation(bottom up)

Mar 14th, 2020
582
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.33 KB | None | 0 0
  1. /*
  2. Leetcode #746
  3. On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
  4.  
  5. Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.
  6.  
  7. Example 1:
  8. Input: cost = [10, 15, 20]
  9. Output: 15
  10. Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
  11. Example 2:
  12. Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
  13. Output: 6
  14. Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].
  15. Note:
  16. cost will have a length in the range [2, 1000].
  17. Every cost[i] will be an integer in the range [0, 999].
  18.  
  19. */
  20. class Solution {
  21.     public int minCostClimbingStairs(int[] cost) {
  22.         int len = cost.length;
  23.         if(len == 0){
  24.             return 0;
  25.         }
  26.         if(len == 1){
  27.             return Math.min(cost[0],cost[1]);
  28.         }else{
  29.             int[] cache = new int[len];
  30.             cache[0] = cost[0];
  31.             cache[1] = cost[1];
  32.             for(int i = 2; i<len; i++){
  33.                 cache[i] = Math.min(cache[i-1]+cost[i], cache[i-2]+cost[i]);
  34.             }
  35.             //return the lower of either the step 1 or 2 steps before the top
  36.             return Math.min(cache[len-1] ,cache[len-2]);
  37.         }
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement