用递归写的,会超时:
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int res = INT_MAX, n = coins.size();
sort(coins.begin(), coins.end());
helper(coins, n - 1, amount, 0, res);
return (res == INT_MAX) ? -1 : res;
}
void helper(vector<int>& coins, int start, int target, int cur, int& res) {
if (target < 0) return;
if (target == 0) {res = min(res, cur); return;}
for (int i = start; i >= 0; --i) {
helper(coins, i, target - coins[i], cur + 1, res);
}
}
};
还是老老实实用动态规划好。。。