Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example;
- import java.util.*;
- public class Main {
- private static HashMap<Integer, HashMap<Integer, Integer>> memoize;
- // private static int combinanation_no_memoize(int n, int k) {
- // if (k == 0 | k == n) { return 1;
- // return combinanation_no_memoize(n - 1, k -1) +
- // combinanation_no_memoize(n - 1, k);
- // }
- // }
- private static int combination(int n, int k) {
- if (memoize == null) {
- memoize = new HashMap<Integer,HashMap<Integer,Integer>>();
- memoize.put(0,new HashMap<Integer, Integer>());
- memoize.get(0).put(0, 1);
- }
- if (!memoize.containsKey(n)) {
- memoize.put(n, new HashMap<Integer, Integer>());
- memoize.get(n).put(0, 1); memoize.get(n).put(n, 1);
- }
- if (!memoize.get(n).containsKey(k) || k > 0 && k < n) {
- int ret = combination(n - 1, k - 1) + combination(n - 1, k);
- memoize.get(n).put(k, ret); return ret;
- }
- return memoize.get(n).get(k);
- }
- private static String leading_space(int row, int number) {
- StringBuilder sb = new StringBuilder();
- for (int i = number; i > row; i--) {
- sb.append("*");
- }
- return sb.toString();
- }
- private static void print_pascal_triangle(int number) {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i <= number; i++) {
- sb.append(leading_space(i, number));
- for (int j = 0; j <= i; j++) {
- sb.append(combination(i, j));
- if (j == i) { break; }
- sb.append("-");
- }
- sb.append("\n");
- }
- System.out.print(sb);
- }
- public static void main(String[] args) {
- print_pascal_triangle(10);
- // System.out.println(memoize);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement