Hey, I have just started learning Dynamic Programming. I solve the problem in this way.
for(i=0;i<21;i++)
for(j=0;j<N;j++)
if(j>=coins[i])
ways[j]+=ways[j-coins[i]];
then I try to solve By recursion. The below code gives me AC.
int makecube ;
i64 dp[22][10000] ;
i64 arr[22];
i64 rec( i64 i , i64 total )
{
if( i >= 21 ) {
if( total == makecube ) {
return 1 ;
} else return 0 ;
}
if( dp[i][total] != -1 )return dp[i][total] ;
i64 ret1 = 0;
i64 ret2 = 0 ;
if( total + arr[i] <= makecube )ret1 = rec( i , total + arr[i] ) ;
ret2 = rec( i+1 , total ) ;
return dp[i][total] = ret1 + ret2 ;
}
int main()
{
for( int i = 1 ; i <= 21 ; i++ )arr[i-1] = i*i*i ;
while( SI( makecube ) == 1 ) {
mem( dp , -1 ) ;
printf("%lld\n",rec( 0 , 0 )) ;
}
return 0;
}
And finally I tried to code like this,
int makecube ;
int arr[] = { 0 , 1 , 8 , 27 , 64 , 125 , 216 , 343 , 512 , 729 , 1000 , 1331 , 1728 , 2197 , 2744 , 3375 , 4096 , 4913 , 5832 , 6859 , 8000 , 9261 } ;
i64 dp[21][10000] ;
i64 rec( i64 i , i64 total )
{
if( total == makecube ) {
return 1 ;
}
if( i == 22 ) {
return 0 ;
}
if( dp[i][total] != -1 )return dp[i][total] ;
i64 ret1 = 0;
for( int j = 1 ;total+j*arr[i] <= makecube ; j++ ) {
ret1 += rec( i+1 , total + j*arr[i] );
}
return dp[i][total] = ret1 ;
}
int main()
{
while( SI( makecube ) == 1 ) {
mem( dp , -1 ) ;
printf("%lld\n",rec( 1 , 0 )) ;
}
return 0;
}
Can anyone please find what is problem for the second recursive solution. This solution even do not give ans for given test cases.