import java.util.Scanner; public class FastSpock { public static long combinations(int n, int k){ // pre: 0 <= k <= n // post: return the number of possible combinations of // k out of n if (n==k || k==0) return 1; else // n>k and k>0 return combinations(n-1,k-1) + combinations(n-1,k); } public static long combinations(int n, int k, long[][] A){ // pre: 0 <= k <= n // post: return the number of possible combinations of // k out of n // A contains previously computed values if(A[n][k]==0){ if (n==k || k==0) A[n][k] = 1; else // n>k and k>0 A[n][k] = combinations(n-1,k-1,A) + combinations(n-1,k,A); } return A[n][k]; } public static void main(String[] args) { // TODO Auto-generated method stub Scanner Input = new Scanner(System.in); int n,k; do{ System.out.println("Enter set size n>0 (0 to finish)"); n = Input.nextInt(); if(n>0) { System.out.println("Enter subset size k <= n"); k = Input.nextInt(); long[][] A = new long [n+1][k+1]; // we are using the fact that A is initialized with 0-s System.out.println("FAST: number of combinations: " + combinations(n,k,A)); System.out.println("SLOW: number of combinations: " + combinations(n,k)); for(int i=1; i<=n; i++){ for(int j=0; j<=k; j++) System.out.printf("%6d ", A[i][j]); System.out.println(); } } } while (n>0); } }