Picking five numbers that sum to S

前端 未结 4 1622
孤街浪徒
孤街浪徒 2021-01-31 10:51

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)

4条回答
  •  Happy的楠姐
    2021-01-31 11:10

    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];
    }
    

提交回复
热议问题