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

后端 未结 3 940
走了就别回头了
走了就别回头了 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条回答
  •  心在旅途
    2020-12-03 13:39

    This problem is equivalent to calculation of Mth coefficient of polynom with given roots (Vieta's theorem). Adapted algorithm in Delphi (O(N) memory and O(N^2) time):

     function CalcMultiComb(const A: array of Integer; const M: Integer): Integer;
      var
        i, k, N: Integer;
        Coeff: TArray;
      begin
        N := Length(A);
        if (N = 0) or (M > N) then
          Exit;
        SetLength(Coeff, N + 1);
    
        Coeff[0] := -A[0];
        Coeff[1] := 1;
        for k := 2 to N do begin
          Coeff[k] := 1;
          for i := k - 2 downto 0 do
            Coeff[i + 1] := Coeff[i] - A[k-1] * Coeff[i + 1];
          Coeff[0] := -A[k-1] * Coeff[0];
        end;
    
        Result := Coeff[N - M];
        if Odd(N - M) then
          Result := - Result;
      end;
    

    calls CalcMultiComb([1, 2, 3, 4], M) with M=1..4 give results 10, 35, 50, 24

提交回复
热议问题