![]() |
VOOZH | about |
Given an array arr[] of N integers and an integer K, the task is to check if the expression formed for any permutation of the given array after assigning arithmetic operators(+, -, /, *) gives the value K or not. If found to be true, then print the order of operations performed. Otherwise, print "-1".
Note: After division operator '/' is applied, the result can be a floating-point number.
Examples:
Input: arr[] = {2, 0, 0, 2}, K = 4
Output: 2 + 0 => 2 + 2 => 4 + 0 => 4Input: arr[] = {1, 2, 4, 7}, K = 50
Output: -1
Approach: The idea is to use Backtracking and find the value of the resultant equation by generating all possible combinations of assigning the operators. Below are the steps:
Below is the implementation of the above approach:
2+0 => 2+2 => 4+0 => 4
Time Complexity: O(N!*4N)
Auxiliary Space: O(N)