The method works as follows:
The first statements are the stopping conditions for the current recursion (without them, for all cases, you end with an infinite loop, which ultimately ends in StackOverFlow)
- . :
count( S, m - 1, n ) (m-1),count( S, m, n-S[m-1]) ,
:
S[] = {1,2)
m = S.length
n = 3
; = count( S, m - 1, n ), = count( S, m, n-S[m-1]):
m=2;n=3
/ \
m=1;n=3 m=2;n=1
/ \ / \
m=0;n=3 m=1;n=2 m=1;n=1 m=2;n=-1
/ \ / \
m=0;n=2 m=1;n=1 m=0;n=1 m=1;n=0
/ \
m=0;n=1 m=1;n=0
Pre-order .
. , n = 0.
:
- m = 1; n = 3 - (2c)
- m = 1; n = 2 - (1c) 1
- m = 1; n = 1 - (1c) 1
- m = 1; n = 0 - (1c) 1
- n = 0 - (3x1c)
- m = 2; n = 1 - (2c) 2
- m = 1; n = 1 - (2c)
- m = 1; n = 0 - (1c) 1
- n = 0 - (1x2c + 1x2c)
node - 0 ( ) 1 () - . , .
:
, :
public static void main(String[] args){
int[] coins = new int[]{1,2};
System.out.println("Final Count = " + count(coins, coins.length, 3, ""));
}
public static int calls = 0;
public static int count( int S[], int m, int n , String from){
calls++;
System.out.print("Call#" + calls + ": " + from + "; m = " + m + "; n = " + n);
if (n == 0)
{
System.out.println(" - Solution Found");
return 1;
}
if (n < 0)
{
System.out.println(" - No Solution Found n < 0");
return 0;
}
if (m <=0 && n >= 1)
{
System.out.println(" - No Solution Found (other Case)");
return 0;
}
System.out.println();
return count( S, m - 1, n , from + "E" ) + count( S, m, n-S[m-1], from + "I" );
}