程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Delphi >> Delphi回溯法找出不同位組合

Delphi回溯法找出不同位組合

編輯:Delphi

Delphi數組例子,Delphi使用回溯法找出n個自然數中取r個數的不同位組合,指定自然數和數組元素就可以算出分組了,演示效果如圖所示:

Delphi數組例子,Delphi使用回溯法找出不同位組合

Delphi數組例子,Delphi使用回溯法找出n個自然數中取r個數的不同位組合的代碼如下:

vIEw source print? 01 unit Unit1; 02 interface 03 uses 04   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, 05   Dialogs, StdCtrls; 06 type 07   TForm1 = class(TForm) 08     Button1: TButton; 09     Edit1: TEdit; 10     Label1: TLabel; 11     Label2: TLabel; 12     Edit2: TEdit; 13     Memo1: TMemo; 14     procedure comb(m,r : integer); 15     procedure Button1Click(Sender: TObject); 16   private 17     { Private declarations } 18   public 19     { Public declarations } 20   end; 21 var 22   Form1: TForm1; 23   a:Array [0..100of integer; 24 implementation 25 {$R *.dfm} 26 procedure TForm1.comb(m, r: integer); 27 var 28   i,j : Integer; 29   s : string; 30 begin 31   i:=0; 32   a[i]:=1; 33   while true do 34   begin 35     if (a[i]-i)<=(m-r+1then 36     begin 37       if i=(r-1then 38       begin 39         s:=''; 40         for j:=0 to r-1 do 41           s := s +IntToStr(a[j])+','; 42         Memo1.Lines.Append(Trim(s)); 43         a[i]:=a[i]+1; 44         continue; 45       end; 46       i:=i+1; 47       a[i]:=a[i-1]+1; 48     end 49     else 50     begin 51       if i=0 then exit; 52       i:=i-1; 53       a[i]:=a[i]+1; 54     end; 55   end; 56 end; 57 procedure TForm1.Button1Click(Sender: TObject); 58 var 59   m,n:Integer; 60 begin 61   m := StrToInt(Edit1.Text); 62   n := StrToInt(Edit2.Text); 63   memo1.Clear; 64   comb(m,n); 65 end; 66 end.
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved