上面就是它的常见公式,很多问题都可以通过计算这个公式直接得到你想要的结果。比如给你了一个这样的题目:已知一个入栈序列为1,2,3,4,5,求所有可能的出栈序列总数有多少?简单的一算就知道了这个就相当于要计算C5 的值了,也许你已经知道答案了。那么我想问:你知道怎么去求出它的所有可能的序列而不是仅仅要出它的总数呢?此时,这个公式将显得无力。那么我们接下来分析一下该如何解决这个问题。当面对比较复杂抽象的问题的时候,我们总是可以通过列举简单的例子来发现解决问题的规律。为了简单起见,我们列举了1,2,3,4,5 这5个数作为入栈的序列,简单分析一下它的过程,也许就知道程序该如何写了,当数字1入栈的时候,此时的栈将面临两个选择,出栈?继续入栈。也就是说任一时刻,对都会面临两种选择,出栈还是入栈?这时,如果你对递归程序有一定的认识的话,也就你对程序的结构已经有思路了。(为了方便利用栈的数据结构采用了C++)
我写的程序大概是这样子的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
#include
<iostream> #include
<stack> using namespace std; static int count; void outprint(stack< int >
q){ while (q.size()!=0)
{ cout
<< q.top() << "->
" ; q.pop(); } cout
<< endl; count++; return ; } //q
存放入栈序列 //stk
用于模拟入栈过程 //output
用于存放可能的出栈序列 void allPopSeq(stack< int >
q,stack< int >
stk,stack< int >
output){ if ((q.size()
== 0)&&(stk.size()==0)&&(output.size() == 5)) { outprint(output); return ; } if (q.size()!=0){ //入栈 int v
= q.top(); stk.push(v);
q.pop(); allPopSeq(q,stk,output); stk.pop(); q.push(v); //回溯恢复 } if (stk.size()!=0)
//出栈 { int v
= stk.top(); stk.pop(); output.push(v); allPopSeq(q,stk,output); output.pop(); stk.push(v); //回溯恢复 } return ; } int main( int argc, char **
argv){ int arr[5]
= {1,2,3,4,5}; stack< int >
stkValues; stack< int >
stkOutput; stack< int >
tmp; int i; for (i
= 0;i!= 5;++i){ stkValues.push(arr[i]);
} allPopSeq(stkValues,tmp,stkOutput); cout
<< count << endl; } |