左神算法基础班4_5折纸问题

Problem:
  【题目】 请把一段纸条竖着放在桌子上,然后从纸条的下边向
  上方对折1次,压出折痕后展开。此时 折痕是凹下去的,即折痕
  突起的方向指向纸条的背面。如果从纸条的下边向上方连续对折
  2 次,压出折痕后展开,此时有三条折痕,从上到下依次是下折
  痕、下折痕和上折痕。
  给定一 个输入参数N,代表纸条都从下边向上方连续对折N次,
  请从上到下打印所有折痕的方向。 例如:N = 1时,打印: down
  N = 2时,打印: down down up

Solution:
  首先,计算折痕次数是很好算的,一共是2^0 + 2^1 + ...+ 2^N
  上下折痕次数也很好算,第一次是下折痕,然后上下折横次数平分总折横次数,下折痕多一次
  但是不知道怎么使用递归
  但是找到规律了,就是在上一次折痕的间隙依次插入下、上n次
  比如:
    第2次折痕为:   下      下     上
    第3次折痕为  下      上     下      上
    即:               下 下 上 下 下 上 上

Code:

  

 1 #pragma once
 2 #include <iostream>
 3 #include <vector>
 4 #include <string>
 5 
 6 using namespace std;
 7 
 8 struct Node
 9 {
10     string str;
11     Node* next;
12     Node(string s = "") :str(s), next(NULL) {}
13 };
14 
15 
16 Node* ZheZhi01(const int N)//非递归方式,使用链表插入更方便
17 {
18     Node* head = new Node("");
19     Node* p;
20     for (int i = 1; i <= N; ++i)
21     {
22         p = head;
23         if (i == 1)//第一次折横
24         {
25             Node* q = new Node("down");
26             q->next = p->next;
27             p->next = q;
28             p = p->next->next;
29         }        
30         while(p)
31         {
32             Node* q1 = new Node("down");
33             q1->next = p->next;
34             p->next = q1;
35             p = p->next->next;
36 
37             Node* q2 = new Node("up");
38             q2->next = p->next;
39             p->next = q2;
40             p = p->next->next;
41         }
42 
43     }
44     return head;
45 }
46 
47 void ZheZhi02(const int N, int i, bool down)//使用递归方式
48 {
49     if (i > N)
50         return;
51     ZheZhi02(N, i + 1, true);
52     if (down)
53         cout << "down" << '\t';
54     else
55         cout << "up" << '\t';
56     ZheZhi02(N, i + 1, false);
57 }
58 
59 
60 void Test()
61 {
62     int N;
63     cout << "请输入折纸次数 N: ";
64     cin >> N;
65 
66     ZheZhi02(N, 1, true);
67 
68 
69     Node* head = NULL;
70     head = ZheZhi01(N);
71     Node* p = head->next;
72     cout << "折纸痕为:" << endl;
73     while (p)
74     {
75         cout << p->str << "\t";
76         p = p->next;
77     }
78     cout << endl;
79 
80 }

转载于:https://www.cnblogs.com/zzw1024/p/11007479.html

猜你喜欢

转载自blog.csdn.net/weixin_33854644/article/details/93462088