Advertisement
Guest User

countWaysDP

a guest
Nov 9th, 2016
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | None | 0 0
  1. public class countWaysDP {
  2.     public static int countWaysDP(int n, int[] map) {
  3.         if (n < 0) {
  4.             return 0;
  5.         } else if (n == 0) {
  6.             return 1;
  7.         } else if (map[n] > -1) {
  8.             return map[n];
  9.         } else {
  10.             map[n] = countWaysDP(n - 1, map) +
  11.                      countWaysDP(n - 2, map) +
  12.                      countWaysDP(n - 3, map);
  13.             return map[n];
  14.         }
  15.     }
  16.     public static int countWaysDP2(int n, int[] map) {
  17.         map[1] = 1; // when n = 1, answer is 1
  18.         map[2] = 2; // when n = 2, answer is 2, (1+1) and (2)
  19.         map[3] = 4; // (1+1+1), (1+2), (2+1), (3)
  20.  
  21.         for(int i = 4;i <= n; i++)
  22.         {
  23.             map[i] = map[i-1] + map[i-2] + map[i-3];
  24.         }
  25.  
  26.         return map[n];
  27.     }
  28.    
  29.     public static int countWaysRecursive(int n) {
  30.         if (n < 0) {
  31.             return 0;
  32.         } else if (n == 0) {
  33.             return 1;
  34.         } else {
  35.             return countWaysRecursive(n - 1) + countWaysRecursive(n - 2) + countWaysRecursive(n - 3);
  36.         }
  37.     }
  38.    
  39.     public static void main(String[] args) {
  40.         for (int i = 0; i < 30; i++) {
  41.             long t1 = System.currentTimeMillis();
  42.             int[] map = new int[30 + 1];
  43.             for (int j = 0; j < map.length; j++) {
  44.                 map[j] = -1;
  45.             }
  46.             int c1 = countWaysDP(i, map);
  47.             long t2 = System.currentTimeMillis();
  48.             long d1 = t2 - t1;
  49.            
  50.        
  51.            
  52.             long t3 = System.currentTimeMillis();
  53.             int c2 = countWaysRecursive(i);
  54.             long t4 = System.currentTimeMillis();
  55.             long d2 = t4 - t3;         
  56.             System.out.println(i + " " + c1 + " " + c2 + " " + d1 + " " + d2);
  57.         }
  58.     }
  59.  
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement