标签:
设有n个整数的集合{1,2,…,n},从中取出任意r个数进行排列(r<n),试列出所有的排列。
1 解法一: 2 program ex5_2; 框架[一] 3 VAR s: set of 1..100; 4 n,r,num:integer; 5 a:array [1..100] of integer; 6 PROCEDURE print; //输出方案 7 var i:integer; 8 begin 9 num:=num+1; 10 for i:=1 to r do 11 write(a[i]:3); 12 writeln; 13 end; 14 PROCEDURE Search(k:integer); //回溯过程 15 VAR i:integer; 16 begin 17 for i:=1 to n do 18 if i in s then //判断i是否可用 19 begin 20 a[k]:=i; //保存结果 21 s:=s-[i]; //从s集合中删除i 22 if k=r then print 23 else Search(k+1); 24 s:=s+[i]; //把i放回s集合中 25 end; 26 end; 27 BEGIN 28 write(‘Input n,r:‘);readln(n,r); 29 s:=[1..n];num:=0; 30 Search(1); 31 writeln(‘number=‘,num); //输出方案总数 32 END. 33 34 35 解法二: 36 program ex5_2; 框架[二] 37 type se=set of 1..100; 38 var s:se; 39 n,r,num,k:integer; 40 a:array [1..100] of integer; 41 PROCEDURE print; 42 //输出方案 43 var i:integer; 44 begin 45 num:=num+1; 46 for i:=1 to r do 47 write(a[i]:3); 48 writeln; 49 end; 50 PROCEDURE Search(s:se;k:integer); 51 //回溯过程 52 VAR i:integer; 53 begin 54 if k>r then print 55 else 56 for i:=1 to n do 57 if i in s then //判断i是否可用 58 begin 59 a[k]:=i; //保存结果 60 Search(s-[i],k+1); //进一步递归,i已放过的信息通过参数进行传递 61 end; 62 end; 63 BEGIN 64 write(‘Input n,r:‘); readln(n,r); 65 s:=[1..n];num:=0; 66 Search(s,1); 67 writeln(‘number=‘,num); //输出方案总数 68 readln; 69 END.
标签:
原文地址:http://www.cnblogs.com/vacation/p/4856236.html