1 /* 2 题目描述: 3 请把纸条竖着放在桌子上,然后从纸条的下边向上方对折,压出折痕后再展开。此时有1条折痕, 4 突起的方向指向纸条的背面,这条折痕叫做“下”折痕 ;突起的方向指向纸条正面的折痕叫做“上”折痕。 5 如果每次都从下边向上方对折,对折N次。请从上到下计算出所有折痕的方向。 6 给定折的次数n,请返回从上到下的折痕的数组,若为下折痕则对应元素为"down",若为上折痕则为"up". 7 测试样例: 8 1 9 返回:["down"] 10 */ 11 /* 12 使用递归实现: 13 折叠n次时的折痕 等于 折叠n-1次时的折痕+“down”+折叠n-1次时的折痕的逆的反 14 n = 1时,折痕为:下; 15 则n = 2时,折痕为:下 下 上; 16 n = 3时,折痕为:下下上 下 下上上; 17 */ 18 19 #include <iostream> 20 #include <vector> 21 #include <string> 22 using namespace std; 23 24 vector<string> foldPaper(int n){ 25 vector<string> fp; 26 if (n == 1){ 27 fp.push_back("down"); 28 return fp; 29 } 30 vector<string> fold = foldPaper(n-1); 31 for (int i = 0; i < fold.size(); i++) 32 fp.push_back(fold[i]); 33 fp.push_back("down"); 34 for (int i = fold.size()-1; i >= 0; i--){ 35 if (fold[i] == "down") 36 fp.push_back("up"); 37 else 38 fp.push_back("down"); 39 } 40 return fp; 41 } 42 43 int main(){ 44 vector<string> result; 45 result = foldPaper(4); 46 for (int i = 0; i < result.size(); i++) 47 cout << result[i] << endl; 48 return 0; 49 }