Amazon Interview Question
Software Engineer / Developersint main()
{
int s[]={1,2,5,10};
int n=6,m=4;
int r=count(n,s,m);
printf("%d",r);
return 0;
}
int count(int n,int *s,int m)
{
if ( n == 0 )
return 1;
if ( n < 0 )
return 0;
if ( m <= 0 && n >= 1 )
return 0;
return count( n,s, m - 1 ) + count( n - s[m-1],s, m );
}
I think as you are not storing the solutions hence :
you will count the same solution as many
like
above method will count
1+5 and 5+1 hence 2 but in the example I think they counted it as single
Sorry a small missing of termination condition
first sort all the coins
vector<int> arr;
int func(int n,int index=0){
if(n<0)
return 0;
if(!n) return 1;
if(index==sz(arr)) return 0;
if(dp[n][index]!=-1) return dp[n][index];
return dp[n][index]=func(n-arr[index],index)+func(n,index+1);
}
int func(int[] d, int ind, int N) {
if(N == 0)
return 1;
if(N < 0)
return 0;
int ways = 0;
for(int i = 0; d[ind]*i < n; i++) {
ways += func(d, ind+1, N-d[ind]*i);
}
return ways;
}
Sorry, one more condition after
"if(N < 0) return 0;"
Add
"if(ind >= d.length) return 0;"
Simple and efficient Solution!!
But, the "for" loop condition should be "d[ind]*i <= n".
Why do we need the for loop condition "d[ind]*i <= n" instead of a normal "i<n"? (Assuming n is length of denomination array)
int coins[4] = { 1,2,5,10};
int noOfDenominations = 4;
void denominations(string s,int remSum, int lastUsedCoinIndex)
{
if(remSum == 0 )
{
cout << s << endl;
return;
}else{
for(int i = lastUsedCoinIndex ; i < noOfDenominations ; i++)
{
if(remSum >= coins[i])
{
char temp[10];
itoa(coins[i],temp,10);
denominations(s+temp,remSum-coins[i],i);
}
}
}
}
'solution' and 'denom'are Global variables or you can also pass them( solution needs to be passed by reference)
vector< vector<int> > solution;
vector<int> denom;
from main call as:
vector<int>sub;
subsum(6,sub,0);
and then
if( numelments(solution) == 0 ) "NOT POssible"
else "nO of WAys = " NUmEL(solution);
find() method can be easily constructed i think
- Aditya October 23, 2010