下面这个方法比穷举好很多,但也挺慢的,主要是我的那个以前计算四则混合运算的函数GetmutBaseValue太复杂,支持的东西太多.支持无穷极括号、许多函数、联接运算等。有空再写个专门的GetmutBaseValue。
type
Set9='1'..'9';
Set9s=set of Set9;
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
const
MutCh:array[0..3] of char=('+','-','*','/');
function GetmutStrValue(st:string):integer;
procedure mutTo100(NowST:string;leaveSet:Set9s;Var sts:Tstringlist);
var
Form1: TForm1;
implementation
{$R *.dfm}
function GetmutStrValue(st:string):integer;
begin
result:=GetmutBaseValue(st,false);
//这是我以前写好的一个计算四则混合运算的函数
end;
procedure mutTo100(NowST:string;leaveSet:Set9s;Var sts:Tstringlist) ;
var
i:integer;
numch:Set9;
ALeaveSet:Set9s;
ANowSt:string;
begin
if (GetmutStrValue(NowST)=100) and (leaveSet=[]) then
begin
//算式等于100,且正好用完9个数
sts.Add(NowST+' =100');
exit;
end;
if leaveSet<>[] then
begin
for i:=0 to 3do
for numch in leaveSetdo
begin
if NowSt='' then
ANowSt:=numch
else
ANowSt:=NowST+mutch+numch;
ALeaveSet:=leaveSet-[numch];
mutTo100(ANowst,ALeaveSet,Sts);
end;
end;
//end if leaveSet<>[]
end;
procedure TForm1.Button1Click(Sender: TObject);
var
sts:Tstringlist;
begin
sts := Tstringlist.Create;
try
mutTo100('',['1'..'9'],sts);
form1.Memo1.Lines.Text:=sts.Text;
finally
sts.Free;
end;
end;
end.