Generate all combinations of mathematical expressions that add to target (Java homework/interview)

前端 未结 3 867
你的背包
你的背包 2021-01-31 05:39

I\'ve tried to solve the problem below for a coding challenge but could not finish it in 1 hour. I have an idea on how the algorithm works but I\'m not quite sure how to best im

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 06:27

    First, you need a method where you can input the expression

    3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8
    

    and get the answer:

    27182
    

    Next, you need to create a tree structure. Your first and second levels are complete.

    3
    31, 3 + 1, 3 - 1, 3 * 1, 3 / 1
    

    Your third level lacks a few expressions.

    31 -> 314, 31 + 4, 31 - 4, 31 * 4, 31 / 4
    3 + 1 -> 3 + 14, 3 + 1 + 4, 3 + 1 - 4, 3 + 1 * 4, 3 + 1 / 4
    3 - 1 -> 3 - 14, 3 - 1 + 4, 3 - 1 - 4, 3 - 1 * 4, 3 - 1 / 4
    3 * 1 -> 3 * 14, 3 * 1 + 4, 3 * 1 - 4, 3 * 1 * 4, 3 * 1 / 4
    3 / 1 -> 3 / 14, 3 / 1 + 4, 3 / 1 - 4, 3 / 1 * 4, 3 / 1 / 4
    

    You can stop adding leaves to a branch of the tree when a division yields a non integer.

    As you can see, the number of leaves at each level of your tree is going to increase at a rapid rate.

    For each leaf, you have to append the next value, the next value added, subtracted, multiplied, and divided. As a final example, here are 5 of the fourth level leaves:

    3 * 1 + 4 -> 3 * 1 + 41, 3 * 1 + 4 + 1, 3 * 1 + 4 - 1, 3 * 1 + 4 * 1,
        3 * 1 + 4 / 1
    

    Your code has to generate 5 expression leaves for each leaf until you've used all of the input digits.

    When you've used all of the input digits, check each leaf equation to see if it equals the value.

提交回复
热议问题