Skip to content

Commit e109866

Browse files
committed
added a recursive solution
1 parent 5c8175e commit e109866

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

algorithms/cpp/coinChange/coinChange.cpp

+20
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,26 @@
2525
* cases.
2626
*
2727
***************************************************************************************/
28+
29+
30+
/* Recursive solution - TIME LIMIT ERROR */
31+
class Solution {
32+
public:
33+
int coinChange(vector<int>& coins, int amount) {
34+
int result = INT_MAX;
35+
if ( amount == 0 ) return 0;
36+
if ( amount < 0 ) return -1;
37+
for (int i=0; i<coins.size(); i++) {
38+
if ( amount - coins[i] < 0 ) continue;
39+
int r = coinChange_recursive(coins, amount - coins[i]);
40+
if ( r == -1 ) continue;
41+
if (result > r ) result = r + 1;
42+
}
43+
return result == INT_MAX ? -1 : result;
44+
}
45+
}
46+
47+
2848
/*
2949
* Solution 1 - O(N * amount)
3050
* =========

0 commit comments

Comments
 (0)