Advertisement
cd62131

print pascal's triangle

Oct 15th, 2013
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.66 KB | None | 0 0
  1. package com.example;
  2. import java.util.*;
  3. public class Main {
  4.   private static HashMap<Integer, HashMap<Integer, Integer>> memoize;
  5. //  private static int combinanation_no_memoize(int n, int k) {
  6. //    if (k  == 0 | k == n) { return 1;
  7. //    return combinanation_no_memoize(n - 1, k -1) +
  8. //      combinanation_no_memoize(n - 1, k);
  9. //    }
  10. //  }
  11.   private static int combination(int n, int k) {
  12.     if (memoize == null) {
  13.       memoize = new HashMap<Integer,HashMap<Integer,Integer>>();
  14.       memoize.put(0,new HashMap<Integer, Integer>());
  15.       memoize.get(0).put(0, 1);
  16.     }
  17.     if (!memoize.containsKey(n)) {
  18.       memoize.put(n, new HashMap<Integer, Integer>());
  19.       memoize.get(n).put(0, 1); memoize.get(n).put(n, 1);
  20.     }
  21.     if (!memoize.get(n).containsKey(k) || k > 0 && k < n) {
  22.       int ret = combination(n - 1, k - 1) + combination(n - 1, k);
  23.       memoize.get(n).put(k, ret); return ret;
  24.     }
  25.     return memoize.get(n).get(k);
  26.   }
  27.   private static String leading_space(int row, int number) {
  28.     StringBuilder sb = new StringBuilder();
  29.     for (int i = number; i > row; i--) {
  30.       sb.append("*");
  31.     }
  32.     return sb.toString();
  33.   }
  34.   private static void print_pascal_triangle(int number) {
  35.     StringBuilder sb = new StringBuilder();
  36.     for (int i = 0; i <= number; i++) {
  37.       sb.append(leading_space(i, number));
  38.       for (int j = 0; j <= i; j++) {
  39.         sb.append(combination(i, j));
  40.         if (j == i) { break; }
  41.         sb.append("-");
  42.       }
  43.       sb.append("\n");
  44.     }
  45.     System.out.print(sb);
  46.   }
  47.   public static void main(String[] args) {
  48.     print_pascal_triangle(10);
  49. //    System.out.println(memoize);
  50.   }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement