Search code examples
puzzle

Number of possible combinations


How many possible combinations of the variables a,b,c,d,e are possible if I know that:

a+b+c+d+e = 500

and that they are all integers and >= 0, so I know they are finite.


Solution

  • @Torlack, @Jason Cohen: Recursion is a bad idea here, because there are "overlapping subproblems." I.e., If you choose a as 1 and b as 2, then you have 3 variables left that should add up to 497; you arrive at the same subproblem by choosing a as 2 and b as 1. (The number of such coincidences explodes as the numbers grow.)

    The traditional way to attack such a problem is dynamic programming: build a table bottom-up of the solutions to the sub-problems (starting with "how many combinations of 1 variable add up to 0?") then building up through iteration (the solution to "how many combinations of n variables add up to k?" is the sum of the solutions to "how many combinations of n-1 variables add up to j?" with 0 <= j <= k).

    public static long getCombos( int n, int sum ) {
      // tab[i][j] is how many combinations of (i+1) vars add up to j
      long[][] tab = new long[n][sum+1];
      // # of combos of 1 var for any sum is 1
      for( int j=0; j < tab[0].length; ++j ) {
        tab[0][j] = 1;
      }
      for( int i=1; i < tab.length; ++i ) {
        for( int j=0; j < tab[i].length; ++j ) {
          // # combos of (i+1) vars adding up to j is the sum of the #
          // of combos of i vars adding up to k, for all 0 <= k <= j
          // (choosing i vars forces the choice of the (i+1)st).
          tab[i][j] = 0;
          for( int k=0; k <= j; ++k ) {
            tab[i][j] += tab[i-1][k];
          }
        }
      }
      return tab[n-1][sum];
    }
    
    $ time java Combos
    2656615626
    
    real    0m0.151s
    user    0m0.120s
    sys 0m0.012s