第一种方法:使用缓存+递归算法.(运度超越5%,内存超5%)
可以说是比较慢了
class Solution {
public:
int **cache;
int coinChange(vector<int>& coins, int amount) {
const int n = coins.size();
cache = new int*[amount+1];
for(int i=0;i<amount+1;i++){
cache[i] = new int[n+1];
}
for(int i=0;i<amount+1;i++){
for(int j=0;j<n+1;j++){
cache[i][j] = -2;
}
}
return coinChange(coins,amount,coins.size());
}
int coinChange(vector<int>& coins, int amount,int n) {
if(amount==0){
return 0;
}
if(amount<0){
return -1;
}
if(n<=0){
return -1;
}
if(cache[amount][n] != -2){
return cache[amount][n];
}
int c;
int min = -1;
c = coinChange(coins,amount,n-1);
if(c!=-1 && min==-1 ||c!=-1 && min>c){
min = c;
}
for(int i=0;i<n;i++){
c = coinChange(coins,amount-coins[i],n);
if(c!=-1 && min==-1 ||c!=-1 && min>c){
min = c+1;
}
}
if(cache[amount][n] == -2){
cache[amount][n] = min;
}
return min;
}
};
第二种方法,一维动态规划(运度超越86%,内存超越86%)
改成一维数组的形式就快了很多。
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int *dp;
dp = new int[amount+1];
for(int i=0;i<amount+1;i++){
dp[i] = -1;
}
for(int i=amount;i>=0;i--){
if(i==amount){
dp[i] = 0;
}else{
for(int j=0;j<coins.size();j++){
long k = coins[j]+(long)i;
if(k<amount+1 && dp[k]!=-1){
dp[i] = dp[i]==-1?1+dp[k]:(min(dp[i],1+dp[k]));
}
}
}
}
return dp[0];
}
};
https://leetcode-cn.com/problems/coin-change/