递归-下楼梯

总时间限制: 1000ms  内存限制: 1000kB
描述
从楼上走到楼下共有h个台阶,每一步有3种走法:走1个台阶,走2个台阶,走3个台阶。问可走出多少种方案,并打印出具体方案?
输入
台阶个数h
输出
各种走法方案及总方案个数
样例输入
5
样例输出       
plan 1:32
plan 2:311
plan 3:23
plan 4:221
plan 5:212
plan 6:2111
plan 7:131
plan 8:122
plan 9:1211
plan 10:113
plan 11:1121
plan 12:1112
plan 13:11111
number of plans : 13
思想:由于每一步的走法次略都相同,可以采用递归的方式。
代码:
 1 #include <iostream>
 2 using namespace std;
 3 
 4 int take[99];
 5 int num = 0;                //方案数
 6 void Try(int i, int s)
 7 {
 8     for(int j=3; j>0; j--)
 9     {
10         if(i>=j)
11         {
12             take[s] = j;
13             if(i==j)
14             {
15                 num++;
16                 cout<<"plan "<<num<<":";
17                 //输出次方案
18                 for(int k=1; k<=s; k++)
19                     cout<<take[k];
20                 cout<<endl;
21             }
22             else //尚未走到楼下
23                 Try(i-j, s+1);
24         }
25 
26     }
27 }
28 
29 int main()
30 {
31     int n;
32     cin>>n;
33 
34     Try(n ,1);
35 
36     cout<<"number of plans :"<<num<<endl;
37     return 0;
38 }

 

posted @ 2015-08-31 23:33  Ustar·Lee  阅读(274)  评论(0编辑  收藏  举报