Computing target number from numbers in a set

后端 未结 7 600
太阳男子
太阳男子 2020-12-13 15:14

I\'m working on a homework problem that asks me this:

Tiven a finite set of numbers, and a target number, find if the set can be used to calculate the target number

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 15:32

    Generally speaking, when you need to do something recursively it helps to start from the "bottom" and think your way up. Consider: You have a set S of n numbers {a,b,c,...}, and a set of four operations {+,-,*,/}. Let's call your recursive function that operates on the set F(S)

    • If n is 1, then F(S) will just be that number.
    • If n is 2, F(S) can be eight things:
      • pick your left-hand number from S (2 choices)
      • then pick an operation to apply (4 choices)
      • your right-hand number will be whatever is left in the set
    • Now, you can generalize from the n=2 case:
      • Pick a number x from S to be the left-hand operand (n choices)
      • Pick an operation to apply
      • your right hand number will be F(S-x)

    I'll let you take it from here. :)

    edit: Mark poses a valid criticism; the above method won't get absolutely everything. To fix that problem, you need to think about it in a slightly different way:

    • At each step, you first pick an operation (4 choices), and then
    • partition S into two sets, for the left and right hand operands,
    • and recursively apply F to both partitions

    Finding all partitions of a set into 2 parts isn't trivial itself, though.

提交回复
热议问题