Sum of multiplication of all combination of m element from an array of n elements

后端 未结 3 935
走了就别回头了
走了就别回头了 2020-12-03 13:06

Suppose I have an array {1, 2, 5, 4} and m = 3. I need to find:

1*2*5 + 1*2*4 + 1*5*4 + 2*5*4

i.e Sum of multipli

3条回答
  •  Happy的楠姐
    2020-12-03 13:44

    I have a Dynamic programming solution in my mind, just want to share. Time complexity is O(k*n^2) with n is total number.

    The idea is, we start to fill in each position from 0 to k -1. So if we assume at position ith, the number to be filled for this position is a, so the sum of all combination start with a will be a times the total of all combination from position (i + 1)th starting with (a + 1)

    Note: I have updated the solution, so it can work with any array data, My language is Java, so you can notice that the index for array is 0 based, which start from 0 to n-1.

    public int cal(int n, int k , int[]data){
       int [][] dp = new int[k][n + 1];
       for(int i = 1; i <= n; i++){
           dp[k - 1][i] = data[i - 1];
       }
       for(int i = k - 2; i >= 0; i--){
           for(int j = 1 ; j <= n; j++){
               for(int m = j + 1 ; m <= n; m++){
                   dp[i][j] += data[j - 1]*dp[i + 1][m];
               }
           }
       }
       int total = 0;
       for(int i = 1; i <= n; i++){
           total += dp[0][i];
       }
       return total;
    }
    

提交回复
热议问题