Place “sum” and “multiply” operators between the elements of a given list of integers so that the expression results in a specified value

前端 未结 3 1333
悲&欢浪女
悲&欢浪女 2021-02-05 15:36

I was given a tricky question. Given: A = [a1,a2,...an] (list of positive integers with length \"n\") r (positive integer)

Find a list

3条回答
  •  抹茶落季
    2021-02-05 16:25

    Let A and B be positive integers. Then A + B ≤ A × B + 1.

    This little fact can be used to construct a very efficient algorithm.

    Let's define a graph. The graph nodes correspond to operations lists, for example, [+, ×, +, +, ×]. There is an edge from graph node X to graph node Y if the Y can be obtained by changing a single + to a × in X. The graph has a source at the node corresponding to [+, +, ..., +].

    Now perform a breadth-first search from the source node, constructing the graph as you go. When expanding a node [+, ×, +, +, ×], for example, you (optionally construct then) connect to the nodes [×, ×, +, +, ×], [+, ×, ×, +, ×], and [+, ×, +, ×, ×]. Do not expand to a node if the result of evaluating it is greater than r + k(O), where k(O) is the number of +'s in the operation list O. This is because of the "+ 1" in the fact at the beginning of the answer - consider the case of a = [1, 1, 1, 1, 1], r = 1.

    This approach uses O(n 2n) time and O(2n) space (where both are potentially very-loose worst case bounds). This is still an exponential algorithm, however I think you will find it performs very reasonably for non-sinister inputs. (I suspect this problem is NP-complete, which is why I am happy with this "non-sinister inputs" escape clause.)

提交回复
热议问题