请把一张纸条竖着放在桌子上,然后从纸条的下边向上方对折1次,压出折痕后展开。此时折痕是凹下去的,即折痕突起的方向指向纸条的背面。如果从纸条的下边向上方连续对折2次,压出折痕后展开,此时有三条折痕,从上到下依次是下折痕、下折痕和上折痕。给定一个输入参数N,代表纸条都从下边向上方连续对折N次,请从上到下打印所有折痕的方向。
[要求]
时间复杂度为
,额外空间复杂度为)
第一行一个整数N。表示对折次数
输出若干行,若该折痕向下,输出"down",否则输出"up"
1
down
2
down down up
// 时间复杂度O(2^N),空间复杂度O(N)
#include<iostream>
using namespace std;
void printProcess(int i, int& n, bool down)
{
if (i > n) return ;
printProcess(i + 1, n, true);
cout << (down ? "down" : "up") << endl;
printProcess(i + 1, n, false);
}
int main()
{
int n; cin >> n;
printProcess(1, n, true);
return 0;
} import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main {
private static int n;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
dfs(1, true);
}
private static void dfs(int depth, boolean isLeft) {
if(depth > n) return;
dfs(depth + 1, true);
System.out.println(isLeft? "down": "up");
dfs(depth + 1, false);
}
} #include <algorithm>
#include <string>
#include <vector>
using namespace std;
void inPrint(vector<bool>& tree,int index)
{
if (index >= tree.size())return;
inPrint(tree, index * 2 + 1);
printf("%s\n", tree[index]?"up":"down");
inPrint(tree, index * 2 + 2);
}
int main()
{
int count = 0;
scanf("%d", &count);
if (count < 0)
{
printf("-1");
return 0;
}
//true为上,false为下
vector<bool> tree(pow(2, count) - 1, false);
int endIndex = 0;
int curIndex = 0;
while (endIndex < tree.size())
{
bool flag = false;
while (curIndex<=endIndex)
{
if (flag)tree[curIndex] = true;
flag = !flag;
curIndex++;
}
endIndex = 2 * (endIndex + 1);
}
inPrint(tree,0);
}