This was asked to me in an interview,
Given a list of integer numbers, a list of symbols [+,-,*,/] and a target number N,
provide an expression which evaluates to N or return False if that is not possible.
e.g. let the list of numbers be [1,5,5] and the target number is 9, one possible
solution could be 5+5-1.
Now, my solution was a brute-force recursive solution that runs through all possible numbers and all possible operations and the recursion terminated either when the number exceeded N or was equal to N.
This got me wondering if there was a better, more refined solution. Any thoughts on this? I was thinking some kind of reverse construction of an expression tree.
1
and+
always present in the input? Does the output must be the shortest? Otherwise you could always return1+1+1+1+1...+1 = n
. – Tollhouse/
integer division? – CarisacarissaO(P(max input number * input size))
pseudopolynomial algorithm whereP
is a polynomial. That would be much better than a exponential backtracking algorithm – Carisacarissa