4 ms·
Coincidentally I was just solving (a variant of) this problem today. The approach I took is taking the list of numbers and recursively replacing each pair (x, y
by sgdpk 7y ago
Coincidentally I was just solving (a variant of) this problem today. The approach I took is taking the list of numbers and recursively replacing each pair (x, y) with x+y (replace + with any operation), until one element remains.
You can separate the process by transforming the list of numbers into a binary tree and applying the operators at the nodes. You then consider all possible binary trees and all combinations of operators.
Bonus: by sorting the input values, you can consider half of the trees, because the operations either commute (x+y = y+x) or don't make sense to reverse in the integers (4/2 vs. 2/4).
- dangoldin 7y ago(Author here) Oh that's pretty clever and better than my approach. I was going to point out that subtraction would still need to be supported but realized we don't need to support negative numbers.
- sgdpk 7y agoExactly :) The polish notation approach is also pretty interesting. I wasn't aware it had the full power of parenthesized expressions. If you are interested I can share my code (simple Python).