OR37. 折纸问题
描述
请把纸条竖着放在桌⼦上,然后从纸条的下边向上⽅对折,压出折痕后再展 开。此时有1条折痕,突起的⽅向指向纸条的背⾯,这条折痕叫做“下”折痕 ;突起的⽅向指向纸条正⾯的折痕叫做“上”折痕。如果每次都从下边向上⽅ 对折,对折N次。请从上到下计算出所有折痕的⽅向。
给定折的次数n,请返回从上到下的折痕的数组,若为下折痕则对应元素为"down",若为上折痕则为"up".
1
返回:["down"]
C++ 解法, 执行用时: 2ms, 内存消耗: 484KB, 提交时间: 2020-12-29
#include <bits/stdc++.h> using namespace std; class FoldPaper { public: void fold(vector<string>&v,int n,string s){ if(n>0){ fold(v,n-1,"down"); v.push_back(s); fold(v,n-1,"up"); } } vector<string> foldPaper(int n) { // write code here vector<string>ans; fold(ans, n, "down"); return ans; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 484KB, 提交时间: 2020-11-22
class FoldPaper { public: vector<string> foldPaper(int n) { vector<string> ret; foldPaper(n, 1, true, ret);// write code here return ret; } private: void foldPaper(int N, int i, bool down, vector<string> & ret) { if (i > N) return; foldPaper(N, i + 1, true, ret); down == true ? ret.push_back("down") : ret.push_back("up"); foldPaper(N, i + 1, false, ret); } };