All possible combinations of OPERATIONS from a given set of numbers that total to a given number

后端 未结 1 1354
野性不改
野性不改 2021-01-17 05:33

I found a lot of post quite similar (referring to the Coin changing Problem) but only using the sum operator. Now imagine you can add, subtract, multiply a

相关标签:
1条回答
  • 2021-01-17 05:57

    Since you only have binary operations, you can model any of the calculations as a binary tree where the leaves are numbers and all other nodes are representing operations, e.g. for your first two examples:

      +                  -
     / \                / \
    9   +              *   +
       / \            /|  / \
      1   +          2 9 -   1
         / \            / \
        4   2          5   4
    

    So your algorithm would need the following parts:

    • a tree generator for all possible binary trees up to a certain node count: starting with a number node, recursively replace each number node (leaf) with an operator node and two children (number nodes), thus generating a sequence of trees like this

    .

    N   O       O       O       ...
       / \     / \     / \
      N   N   O   N   N   O
             / \         / \
            N   N       N   N
    
    • a "tree filler" that generates for a given binary tree (like above) all possible insertions of operations and numbers, like:

    .

      O    :    +     +    ...  -  ...
     / \       / \   / \       / \
    N   N     1   5 1   2     1   5
    
    • a tree evaluator that calculates the result

    Happy programming! :-)

    0 讨论(0)
提交回复
热议问题