1

I have an array such as below:

int[] numberArray = {9,2,1,5,6};

I want to devise a method that will take an integer as an argument and return true/false depending if the argument can be achieved by summing any of the numbers in that array.

public boolean sumCheck (int sum) {
    // ...
}

For example, if sum were 5, sumCheck would return true since numberArray[3] == 5. If sum were 12, sumCheck would return true since numberArray[0]+numberArray[1]+numberArray[2] == 12. It would not return true, however, if sum were 4, as no combination of numberArray elements can sum to this number.

gator
  • 3,465
  • 8
  • 36
  • 76

2 Answers2

4

This is the subset sum problem, which is NP-complete. However, you can find a pseudo-polynomial time algorithm (a variant of knapsack, using DP) on the Wiki page.

zw324
  • 26,764
  • 16
  • 85
  • 118
1

Check http://www.geeksforgeeks.org/dynamic-programming-subset-sum-problem/..it explains your problem in a nice way. First brute force then dp solution is there.

Kartik Goyal
  • 459
  • 3
  • 15