Given a list of 'N' coins, their values being in an array A[], return the minimum number of coins required to sum to 'S' (you can use as many coins you want). If it's not possible to sum to 'S', return -1
For Example, input N coins array { 1, 3, 5 } and S as 11, the answer should be 3
My Answer: (I am not sure if it is correct.)
int minCoins(int* a, int count, int target)
{
int N = count;
int S = target;
int *mina=NULL;
mina = new int[S+1];
mina[0]=0;
for(int i=1;i<=S;i++)
{
mina[i]=-1;
for(int j=0;j<N;j++)
{
if(a[j]<=i && mina[i-a[j]] != -1)
{
if(mina[i]==-1 || mina[i-a[j]]+1 < mina[i])
{
mina[i] = mina[i-a[j]]+1;
}
}
}
}
return mina[S];
}
沒有留言:
張貼留言