有一组数A,如:(1,4,4,3,6,2,5,9)
求该组数中元素之和为某一值m (如6 )的所有序列如:6=2+4,则(2,4)为一组合格要求的序列,则A关于m=6的序列共有以下几组
(1,2,3)
(1,5)
(2,4)及第二组(2,4)能否,找到一算法求出A关于m的所有组合呢,
(注意:数组A内的元素为浮点数,元素可重复)谢谢指点!不胜感激!

解决方案 »

  1.   

    //这种组合可以看成集合,用1表示有,0表示没有~~
    //有的才计算合计,最后的合计和目标相等就输出~~
    //'000000000000' -> '000000000001' -> ... ... -> '111111111111'~~
    //其实就是二进制的表达~~procedure TForm1.Button1Click(Sender: TObject);
      procedure Calc(A: array of Real; mDest: Real);
      var
        I, L: Integer;
        S, T, W: string;
        K: Real; //合计
      begin
        L := Length(A);
        if L <= 0 then Exit;
        S := StringOfChar('0', Length(A)); //初始为000000000000
        T := StringOfChar('1', Length(A)); //终止为111111111111
        while S < T do begin      for I := Length(S) downto 1 do //每次加~~
            if S[I] = '1' then
              S[I] := '0'
            else begin
              S[I] := '1';
              Break;
            end;      K := 0;
          W := '';
          for I := 1 to Length(S) do
            if S[I] = '1' then begin
              K := K + A[Low(A) + I - 1];
              W := Format('%s+%f(%d)', [W, A[Low(A) + I - 1], Low(A) + I - 1]);
            end;
          if Abs(K - mDest) <= 0.000000000001 then //浮点数不能直接判断相等~~
            Memo1.Lines.Add(Copy(W, 2, MaxInt));
        end;
      end;
    begin
      Memo1.Clear;
      Calc([1, 4, 4, 3, 6, 2, 5, 9], 6);
    end;