Writing an algorithm to decide whether a target number can be reached with a set of other numbers and specific operators?

前端 未结 3 1988
有刺的猬
有刺的猬 2020-12-09 07:01

I\'m trying to learn more about algorithm design, and I\'ve set myself the challenge of creating a simple game that presents users with an array of numbers, a target number,

3条回答
  •  甜味超标
    2020-12-09 07:22

    You are facing a more generalized problem of the Partition Problem, which is NP-Complete.

    The Partition Problem is: Given n numbers, split them into two (distinct) groups A and B such that sum(A) = sum(B). Now, it is easy to see that if you have a problem with +,- operators and target number 0 - this is basically the same problem, and there is an immidiate reduction from Partition Problem to your problem.

    From this we can conclude your problem is NP-Hard as well, and there is no known polynomial solution for your problem.

    Alternatives are:

    1. Brute Force (As suggested by @Sayakiss)
    2. Depending on the operators - you might be able to use some branch and bound techniques.
    3. For Partition Problem there is pseudo-polynomial Dynamic Programming solution, that might be utilized in here as well, at least for some of the cases.

    Sorry if it's bad news -but at least you won't be looking for something that (most computer scientists believe) is not there

提交回复
热议问题