Question:
Given an array with positive integers and another integer for example{7 2 4} 9, you are required to generate an equation, by inserting operator add ("+") and minus ("-") among the array . The left side of equation are consist of the array and the right side of equation is the integer. here the result is 7-2+4=9
Rules:
Don't include any space in the generated equation.
In case there is no way to create the equation, please output "Invalid". For example {1 1} 10, output is "Invalid"
The length of the integer array is from 1 to 15( include 1 and 15). If the length is 1, for example the input {7} 7, the output is 7=7
There is no operator "+" or "-" in front of the first number:
Don't change the order of the numbers. For example: {7 2 4} 9. 7-2+4=9 is correct answer, 4-2+7=9 is wrong answer.
There could be multiple input, meaning your function could be called multiple times. Do remember print a new line after the call.
Sample Input and Output:
Input:
1 2 3 4 10
1 2 3 4 5
Output:
1+2+3+4=10
Invalid
Solution:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void judge(int sum1, int *arr, char *op, int idx, int n, int sum2)
{
if(idx == n)
{
if(sum1 == sum2)
{
int i=0;
printf("%d", arr[0]);
for(i=1; i<n; i++)
{
printf("%c%d", op[i], arr[i]);
}
printf("=%d\n", sum2);
}
return;
}
op[idx] = '+';
judge(sum1+arr[idx], arr, op, idx+1, n, sum2);
op[idx] = '-';
judge(sum1-arr[idx], arr, op, idx+1, n, sum2);
}
static void ArraySum(int *arr, int n, int sum)
{
char *op = (char *)malloc(n);
memset(op, '+', n);
judge(arr[0], arr, op, 1, n, sum);
free(op);
}
int main()
{
int arr[] = {1,2,3,4};
ArraySum(arr, 4, 5);
return 0;
}