本文整理自网络,侵删。
主要思想:
求从n个数组任意选取一个元素的所有组合,对于这个问题,我们在直观上感觉很容易,但是用程序实现时则发现用for循环解决不了问题,因为n是随意的。在这里,我们用递归的思想,对于数据[1, 3, 4]; [2, 5]; [6, 7];我们可以1.将1,2,6压入栈中,然后输出栈中所有元素,之后弹出62.压入7,输出栈中所有元素,之后弹出73.弹出2,压入5,再压入6,然后输出栈中所有元素,之后弹出64.压入7,输出栈中所有元素,之后弹出7
以此类推,即可得到所有组合。
interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TStr = array[0..2] of ShortString; type TForm1 = class(TForm) Button1: TButton; Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } DcIntArr : array of array of ShortString; //备选集合 DcIntArrCount:Integer;//备选集合数目 ResultIntArr : TStr; //每一个组合的结果 ResultCount : Integer;//总组合数 procedure myshow(tmpResultIntArr:TStr;curr:Integer); end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject);begin DcIntArrCount := 3; ResultCount := 0; //初始化一个二维数组作为备选集合 总组合数目应该为 2*3*2 //实现从(1,2)、(3,4,5)、(6,7)三个集合中任取一个元素,生成组合 //例如(1,3,6)、(1,3,7)... 将每一个组合存储在ResultIntArr中输出 SetLength(DcIntArr,DcIntArrCount); SetLength(DcIntArr[0],2); DcIntArr[0][0] := '1'; DcIntArr[0][1] := '2'; SetLength(DcIntArr[1],3); DcIntArr[1][0] := '3'; DcIntArr[1][1] := '4'; DcIntArr[1][2] := '5'; SetLength(DcIntArr[2],2); DcIntArr[2][0] := '6'; DcIntArr[2][1] := '7'; end; procedure TForm1.myshow(tmpResultIntArr:TStr;curr:Integer);var i : Integer; tmps : ShortString;begin if (curr = DcIntArrCount) then begin tmps := ''; //输出每一种组合至memo中显示 for i := 0 to Length(tmpResultIntArr) - 1 do begin if tmps='' then tmps := tmpResultIntArr[i] else tmps := tmps + ','+ tmpResultIntArr[i]; end; Memo1.Lines.Add(tmps); Inc(ResultCount); Memo1.Lines.Add('第'+IntToStr(ResultCount)+ '个组合-------------------'); Memo1.Lines.Add(''); end else begin for I := 0 to Length(DcIntArr[curr]) - 1 do begin tmpResultIntArr[curr] := DcIntArr[curr][i]; myshow(tmpResultIntArr, curr+1); end; end; end; procedure TForm1.Button1Click(Sender: TObject);begin Memo1.Lines.Clear; myshow(ResultIntArr,0); end; end.
――――――――――――――――
原文链接:https://blog.csdn.net/lotusyangjun/article/details/35231359
相关阅读 >>
Delphi system.net.httpclient 下载
Delphi datetimetogmt gmt时间与tdatetime转换
更多相关阅读请进入《Delphi》频道 >>