Given an array A
of N
nonnegative numbers, I\'m interested in finding the number of ways you can pick 5 numbers (from distinct positions in the array)
You can do it in O(N*S) with dynamic programming:
static int count(int[] A, int S) {
final int K = 5;
// In count[n][s] we'll count the number of ways you can pick n numbers such that their sum is s
int[][] count = new int[K+1][S+1];
count[0][0] = 1; // The base case
for (int i = 0; i < A.length; i++)
for (int n = K; n >= 1; n--)
for (int s = A[i]; s <= S; s++)
count[n][s] += count[n-1][s - A[i]];
return count[K][S];
}