要求:输入参数是总数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.