Given an array A, suppose {5, 5, 4, 3, 7}, use operation {*, /, + -} on 5, 5, 4, 3 and get the result as 7. If it is possible, print the answer. If it is not, return 0.
Answer : 5 * 5 - 4 / 3 = 7.
I solved this using recursion, brute force, checking all the cases.
My code :
void check_result(int* arr, int size, char* op, int depth, int result, int val)
{
if(depth==size)
{
if(val==result)
{
// call function to print pattern of op[]
}
return ;
}
else
{
op[depth]='+';
check_result( arr+1, size, op, depth+1, result, val + *arr );
op[depth]='-';
check_result( arr+1, size, op, depth+1, result, val - *arr );
op[depth]='*';
check_result( arr+1, size, op, depth+1, result, val * (*arr) );
op[depth]='/';
if( *arr )
check_result( arr+1, size, op, depth+1, result, val / (*arr) );
}
}
Can you tell me dynamic approach of this question, because this takes O(4^n) time.
The state should be
DP[position][currentValue]. It means if that the neededResult can be achieved if you are at the correspondingpositionand havingcurrentValue.You can then restore the result in another method:
P.S. This is only PSEUDOCODE. There may be errors and missed corner cases.