请教一个算法(50分)

W

windart

Unregistered / Unconfirmed
GUEST, unregistred user!
编写一个程序,它接受用户输入的一个英文单词(长度不超过20个字符),然后输出由这个
单词的各个字母所组成的所有排列。有两个条件:第一、这个单词的各个字母允许有相同的
;第二、不能输出重复的排列。
请输入一个英文单词:bob
bob
bbo
obb
C或pascal都成 我信箱:cao_sfs@sina.com 实在是穷,给不了您分了
 
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Edit1: TEdit;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

TConfusion=class
private
FInputStr:string;
FOutputList:TStringList;
class procedure Swap(var a:char ;
var b:char);overload;
procedure Perm(s:string;first,last:LongInt);
function GetOutputList:TStringList;
public
Constructor Create(str:string='');
destructor Destroy;
override;
published
property InputStr:string read FInputStr write FInputstr;
property OutputList:TStringList read GetOutputList write FOutputList;
end;

var
Form1: TForm1;
implementation
{$R *.dfm}

class procedure TConfusion.Swap(var a:char ;
var b:char);
var
t:char;
begin
t:=a;
a:=b;
b:=t;
end;

procedure TConfusion.Perm(s:string;first,last:LongInt);
var
i:integer;
begin
if first=last then
begin
if FOutputList.IndexOf(s)=-1 then
begin
FOutputList.Add(s);
end;
end
else
begin
for i:=first to lastdo
begin
Swap(s[first],s);
Perm(s,first+1,last);
Swap(s[first],s);
end;
end;
end;

Constructor TConfusion.Create(str:string='');
begin
FOutputList:=TStringList.Create;
FInputStr:=str;
end;

destructor TConfusion.Destroy;
begin
FOutputList.Free;
end;

function TConfusion.GetOutputList:TStringList;
begin
if FInputStr='' then
Raise Exception.Create('字符串为空');
Perm(FInputStr,1,Length(FInputStr));
Result:=FOutputList;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
cf:TConfusion;
begin
cf:=TConfusion.Create(edit1.Text);
memo1.Text:= cf.OutputList.Text;
cf.Free;
end;

end.
 
摆明了用递归比较简单嘛
 
虽然不是我所希望的结果,但是很感谢testnet,题目中有一点我没说清,这个算法用递归
自然没什么争议,但是如何剔除重复的排列呢?我最不希望的就是保存以前所有的排列,然
后每得到一个新排列就在以前的输出中便历一次,发现重复则不输出。testnet,当你输入
一个长字符串的时候,你会发现你的程序响应的很慢,比如12个字符的时候。
[^]在递归当中如何加上判断条件,从而根本不进行肯定是重复的排列,这是我问这个问题的本
意。
感谢testnet,分给您加上了,谢谢
 
在GetOutputList第一句写上
FOutputList.Clear;清空以前的记录.
在Create(str:string='');中加入inherited Create;
在Destroy中加入 inherited Destroy;
减少内存over flow;
在Perm(s:string;first,last:LongInt);加入
Application.ProcessMessages;可在响应感觉上好点。
 
顶部