Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>@Torlack, @Jason Cohen: Recursion is a bad idea here, because there are "overlapping subproblems." I.e., If you choose <code>a</code> as <code>1</code> and <code>b</code> as <code>2</code>, then you have 3 variables left that should add up to 497; you arrive at the same subproblem by choosing <code>a</code> as <code>2</code> and <code>b</code> as <code>1</code>. (The number of such coincidences explodes as the numbers grow.)</p> <p>The traditional way to attack such a problem is <a href="http://en.wikipedia.org/wiki/Dynamic_programming" rel="nofollow noreferrer">dynamic programming</a>: 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 <em>n</em> variables add up to <em>k</em>?" is the sum of the solutions to "how many combinations of <em>n-1</em> variables add up to <em>j</em>?" with 0 &lt;= <em>j</em> &lt;= <em>k</em>). </p> <pre><code>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 &lt; tab[0].length; ++j ) { tab[0][j] = 1; } for( int i=1; i &lt; tab.length; ++i ) { for( int j=0; j &lt; 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 &lt;= k &lt;= j // (choosing i vars forces the choice of the (i+1)st). tab[i][j] = 0; for( int k=0; k &lt;= j; ++k ) { tab[i][j] += tab[i-1][k]; } } } return tab[n-1][sum]; } </code></pre> <pre> $ time java Combos 2656615626 real 0m0.151s user 0m0.120s sys 0m0.012s </pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload