增强版:
function TForm1.MyCal(He:Integer;//和值
N:Integer; //可加次数
StrPre:String=''):TStringList;
var i,HeMin,iDiv,NA,NB:Integer;
SL_Sub:TStringList;
S:String;
begin
Result:=TStringList.Create;
SL_Sub:=TStringList.Create;
HeMin:=0;
iDiv:=(He Div N)+1;
if StrPre='' then S:=''
else S:=StrPre+',';
for i:=1 to N-1 do HeMin:=HeMin+i;
for i:=iDiv to He-HeMin do begin
if N=2 then begin
Result.Add(S+inttostr(i)+','+inttostr(He-i));
end else begin
SL_Sub:=MyCal(He-i,N-1,StrPre+','+inttostr(i));
Result.Add(S+inttostr(i)+',('+SL_Sub.CommaText+')');
end;
end;
end;
procedure TForm1.MyCalculate(Source:String;SL:TStringList);
var SL_Sub:TStringList;
i,iPos,jPos1,jPos2:Integer;
S:String;
begin
iPos:=Pos('(',Source);
if iPos=0 then begin
SL.Add(Source);
exit;
end;
SL_Sub:=TStringList.Create;
S:=Source;
while iPos>0 do begin
S:=Copy(S,iPos+1,Length(S));
jPos1:=Pos('(',S);
jPos2:=Pos(')',S);
if jPos2=0 then Break;
if jPos1=0 then begin
SL.Add(Copy(S,1,jPos2-1));
exit;
end else begin
if jPos2<jPos1 then begin
SL.Add(Copy(S,1,jPos2-1));
S:=Copy(S,jPos2+1,Length(S));
end else
S:=Copy(S,jPos1+1,Length(S));
end;
end;
end;
procedure Splite(s,SpliteStr:string;L:TStringlist);
Var I:INTEGER;
begin
l.Clear;
i:=pos(SpliteStr,s);
while i>0 do begin
L.Add(copy(s,1,i-1));
delete(s,1,i);
i:=pos(SpliteStr,s);
end;
L.Add(s);
end;
function JudgeDupli(Source:String):Boolean;
var i,j1,j2,j3:Integer;
SL:TStringList;
S,SV:String;
begin
SL:=TStringList.Create;
Splite(Source,',',SL);
S:=','+stringreplace(Source,',',',,',[rfReplaceAll])+',';
for i:=0 to SL.Count-1 do begin
SV:=','+SL+',';
SV:=StringReplace(S,SV,'',[rfReplaceAll]);
j1:=Length(S);
j2:=Length(','+SL+',');
j3:=Length(SV);
if j1-j2>j3 then begin
Result:=True;
exit;
end;
end;
Result:=False;
end;
function ReturnFormat(Source:String):String;
var i:Integer;
S:String;
begin
S:=stringreplace(Source,'"','',[rfReplaceAll]);
while Copy(S,1,1)=',' do
S:=Copy(S,2,Length(S));
while Copy(S,Length(S),1)=',' do
S:=Copy(S,1,Length(S)-1);
if JudgeDupli(S) then Result:=''
else Result:=S;
end;
procedure TForm1.Button1Click(Sender: TObject);
var i,j,m:integer;
SL,SL_Return,SL_Value:TStringList;
S:String;
begin
SL:=TStringList.Create;
SL_Return:=TStringList.Create;
SL_Value:=TStringList.Create;
for m:=2 to 7 do begin
SL.Clear;
SL_Return.Clear;
SL_Value.Clear;
SL:=MyCal(30,m);
for i:=0 to SL.Count-1 do
MyCalculate(SL,SL_Return);
for i:=0 to SL_Return.Count-1 do begin
SL.Clear;
Splite(SL_Return,'","',SL);
for j:=0 to SL.Count-1 do begin
S:=ReturnFormat(SL[j]);
if S<>'' then SL_Value.Add(S);
end;
end;
S:='';
for i:=0 to SL_Value.Count-1 do begin
if S='' then S:='('+SL_Value+')'
else S:=S+',('+SL_Value+')';
end;
Memo1.Lines.Add(S);
end;
end;