Skip to content

Commit 74accf7

Browse files
committed
Merge pull request Show-Me-the-Code#191 from Turkingwang/master
走楼梯问题
2 parents 84ec1cf + 0772c3e commit 74accf7

1 file changed

Lines changed: 102 additions & 0 deletions

File tree

‎AK-wang/A0001/floor_step.C‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
/*
2+
3+
下楼问题。从楼上走到楼下共有h个台阶,每一步有三种走法:
4+
走1个台阶,走2个台阶,走3个台阶。问有多少可走的方案。用递归思想和迭代思想编程。
5+
6+
*/
7+
8+
#include <stdio.h>
9+
#include <string.h>
10+
#include <stdlib.h>
11+
12+
static int stack[1024]; // 存放每一步的台阶数
13+
static int steps = 0; // 走过的步数
14+
static int num_of_method = 0; // 多少种走法
15+
//递归详细版本,列出每一种走法的步骤
16+
void NextStairs(int n)
17+
{
18+
if(n == 0)
19+
{
20+
/* 走完所有台阶,打印本次的走法,即曾经走过的步骤 */
21+
printf("第%3d种走法[需%3d步] : ", ++num_of_method, steps);
22+
int i;
23+
for(i=0; i<steps; i++)
24+
printf("%d ", stack[i]);
25+
printf("\n");
26+
27+
return;
28+
}
29+
30+
if(n >= 1)
31+
{
32+
stack[steps++] = 1; // 本次走1个台阶
33+
NextStairs(n-1);
34+
steps --;
35+
}
36+
if(n >= 2)
37+
{
38+
stack[steps++] = 2; // 本次走2个台阶
39+
NextStairs(n-2);
40+
steps --;
41+
}
42+
if(n >= 3)
43+
{
44+
stack[steps++] = 3; // 本次走3个台阶
45+
NextStairs(n-3);
46+
steps --;
47+
}
48+
}
49+
//迭代法
50+
//此处是归纳出下一次z的迭代规律,下一次的z的值是上一次x,y,z的和,然后每次都要更新x,y,z
51+
int fib3(int n)
52+
{
53+
54+
int x = 0, y = 0,z=1;
55+
int w, k;
56+
57+
for (int j = 0; j < n; j++)
58+
{
59+
60+
w = z;
61+
k = y;
62+
z = x + y + z;
63+
y = w;
64+
x = k;
65+
66+
67+
}
68+
69+
return z;
70+
71+
}
72+
//递归法
73+
int dfib1(int n)
74+
{
75+
if (n < 1)
76+
{ return 0; }
77+
78+
if (n == 1)
79+
return 1;
80+
if (n == 2)
81+
return 2;
82+
if (n == 3)
83+
return 4;
84+
return dfib1(n - 1) + dfib1(n - 2) + dfib1(n-3);
85+
}
86+
87+
int main()
88+
{
89+
int n;
90+
printf("enter a positive number: n=");
91+
scanf("%d", &n);
92+
93+
//NextStairs(n);
94+
//printf("%d\n", dfib1(n));
95+
printf("%d\n", fib3(n));
96+
97+
return 0;
98+
}
99+
100+
101+
102+

0 commit comments

Comments
 (0)