Given a string consisting of number, add + or – sign to make the expression values 0. Return the expression.
For example,
123 => 1 + 2 -3 = 0
173956 => 17 + 39 – 56 = 0
I have no clues to solve this problem other than a brute-force way.
Is there any suggestion?
This is a search problem. Search must be performed in the solution space.
Suppose we starting from ‘123’ string, at this point, we can add + or – sign after ‘1’, as result we get ‘1 + 23’ or ‘1 – 23’. Every variant can be split further by adding a sign after next character. As result, all possible sign additions will form tree-like structure – the solution space. Your algorithm must search solution in this structure. I think A* can be used to do this.
Anders K draw nice ASCII graph of the solution space, you just need to search it for solution. Simple breadth first search or depth first search can do the work, but I think it will be slow if solution space is large.
Also, I think that is possible to find more optimal, specific solution that exploits properties of the solution space, for example – it’s tree-like structure.