This is a recursive function I wrote that can compute the ways of coin change, and it can work perfectly.
int cc(int n, int k)
{
if (n < 0 || k == 0)
return 0;
else if (n == 0)
return 1;
else
{
/*** WAY 1 : START ***/
s.stk[++s.top] = k;
int tmp = cc(n - d[k - 1], k);
s.top--;
return tmp + cc(n, k - 1);
/*** WAY 1 : END ***/
}
}
But, why it starts getting wrong answers if I change the code between two comments as follows:
/*** WAY 2 ***/
return (s.stk[++s.top] = k, cc(n - d[k - 1], k)) + (s.top--, cc(n, k - 1));
// |<----- A ----->| |<----- B ----->|
Aren't they equivalent?
P.S. Though it is not a good way to write like that (way 2), I just wonder why it can't work.
EDIT:
Though we don't know that whether A
or B
will do first, I tried to do some experiments.
The conclusion is that neither return A+B;
nor return B+A;
will get correct answers.