Here's the first part:
bool coinChangeFn(vector<int>& coins, int amount, int level, int& result) {
if (amount < 0) {
cout << "Amount is less than 0!" << endl;
return false;
}
if (amount == 0) {
cout << "Amount is 0. Level is " << level << endl;
result = min(result, level);
return true;
}
bool flag = false;
for (auto coin : coins) {
cout << "Amount: " << amount
<< " Level: " << level
<< " Coin: " << coin
<< endl;
bool temp = coinChangeFn(coins, amount - coin, level + 1, result); // THIS LINE
flag = flag || temp; // THIS LINE
}
return flag;
}
int coinChange(vector<int>& coins, int amount) {
int result{INT_MAX};
return coinChangeFn(coins, amount, 0, result) ? result : -1;
}
And here's the second version of the code
bool coinChangeFn(vector<int>& coins, int amount, int level, int& result) {
if (amount < 0) {
cout << "Amount is less than 0!" << endl;
return false;
}
if (amount == 0) {
cout << "Amount is 0. Level is " << level << endl;
result = min(result, level);
return true;
}
bool flag = false;
for (auto coin : coins) {
cout << "Amount: " << amount
<< " Level: " << level
<< " Coin: " << coin
<< endl;
flag = flag || coinChangeFn(coins, amount - coin, level + 1, result); // THIS LINE
}
return flag;
}
int coinChange(vector<int>& coins, int amount) {
int result{INT_MAX};
return coinChangeFn(coins, amount, 0, result) ? result : -1;
}
I've marked the code under question as "THIS LINE" in the comments. I expected them to have the same behavior, however the first version stopped the recursion earlier than expected.