堆栈以abcd顺序入栈,如何求所有合法的出栈序列
LeeChange:昨天的货箱用了非递归的,今天就用个递归的吧.
program Project2;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
TIntegerArr = array [1..4] of Integer;
var
PopedList: TIntegerArr;
Stack: TIntegerArr;
procedure TryDoIt(PopedIndex, UnPushIndex, StackTop: Integer; Stack: TIntegerArr);
var
i: Integer;
begin
if PopedIndex=5 then
begin
for i:=1 to 4 do
Write(Chr(Ord('a')-1+PopedList[i]), ' ');
WriteLn;
Exit
end;
if StackTop>0 then
begin
PopedList[PopedIndex]:=Stack[StackTop];
TryDoIt(PopedIndex+1, UnPushIndex, StackTop-1, Stack)
end;
if UnPushIndex<=4 then
begin
Stack[StackTop+1]:=UnPushIndex;
TryDoIt(PopedIndex, UnPushIndex+1, StackTop+1, Stack)
end;
end;
begin
TryDoIt(1, 1, 0, Stack);
ReadLn
end.
另外,任何结果字符串的子串也是合法串.