Delphi实现的最佳组合算法

要求:输入参数是总数n,和数组a
运算后得到最佳组合数组和差异值,组合数组的总和要大于等于n,差异值为组合数组的总和-n的差值
如果数组a=[10,20,30,35,100,200,300,2000]
如果n为150的话,输出[20,30,100],差异值为0
如果n为160的话,输出[10,20,30,100],差异值为0
如果n为159的话,输出[10,20,30,100],差异值为1

uses
  System.SysUtils, System.Generics.Collections;

procedure FindBestCombination(arr: TArray<Integer>; n: Integer;
  var bestCombo: TList<Integer>; var minDiff: Integer; combo: TList<Integer>; sum, startIdx: Integer);
var
  i, currentDiff: Integer;
begin
  // 如果当前组合的和大于或等于目标值,检查是否为最佳组合
  if sum >= n then
  begin
    currentDiff := sum - n;
    if currentDiff < minDiff then
    begin
      minDiff := currentDiff;
      bestCombo.Clear;
      bestCombo.AddRange(combo);
    end;
    Exit;
  end;

  // 遍历数组中的每一个元素,尝试添加到当前组合中
  for i := startIdx to Length(arr) - 1 do
  begin
    combo.Add(arr[i]);
    FindBestCombination(arr, n, bestCombo, minDiff, combo, sum + arr[i], i + 1);
    combo.Delete(combo.Count - 1); // 回溯
  end;
end;

function GetBestCombination(arr: TArray<Integer>; n: Integer): string;
var
  bestCombo: TList<Integer>;
  combo: TList<Integer>;
  minDiff: Integer;
  i: Integer;
  resultStr: string;
begin
  bestCombo := TList<Integer>.Create;
  combo := TList<Integer>.Create;
  try
    minDiff := MaxInt;

    FindBestCombination(arr, n, bestCombo, minDiff, combo, 0, 0);

    resultStr := '组合: [';
    for i := 0 to bestCombo.Count - 1 do
    begin
      resultStr := resultStr + bestCombo[i].ToString;
      if i < bestCombo.Count - 1 then
        resultStr := resultStr + ', ';
    end;
    resultStr := resultStr + '], 差异值: ' + minDiff.ToString;

    Result :=inttostr(n)+','+ resultStr;
  finally
    bestCombo.Free;
    combo.Free;
  end;
end;

procedure TestBestCombination;
var
  arr: TArray<Integer>;
  resultStr: string;
begin
  arr := [10, 20, 35, 35, 152, 200, 300, 2000];
  writeln('arr := [10, 20, 35, 35, 152, 200, 300, 2000];');
  resultStr := GetBestCombination(arr, 150);
  WriteLn(resultStr); // 输出: 组合: [20, 30, 100], 差异值: 0

  resultStr := GetBestCombination(arr, 160);
  WriteLn(resultStr); // 输出: 组合: [10, 20, 30, 100], 差异值: 0

  resultStr := GetBestCombination(arr, 159);
  WriteLn(resultStr); // 输出: 组合: [10, 20, 30, 100], 差异值: 1

  resultStr := GetBestCombination(arr, 170);
  WriteLn(resultStr); // 输出: 组合: [10, 20, 35, 100], 差异值: 5

  resultStr := GetBestCombination(arr, 300);
  WriteLn(resultStr);
  resultStr := GetBestCombination(arr, 450);
  WriteLn(resultStr);

  resultStr := GetBestCombination(arr, 1450);
  WriteLn(resultStr);

end;

begin
  TestBestCombination;
end.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值