题目描述
请把纸条竖着放在桌⼦上,然后从纸条的下边向上⽅对折,压出折痕后再展 开。此时有1条折痕,突起的⽅向指向纸条的背⾯,
这条折痕叫做“下”折痕 ;突起的⽅向指向纸条正⾯的折痕叫做“上”折痕。如果每次都从下边向上⽅ 对折,对折N次。请从上到下计算出所有折痕的⽅向。
给定折的次数n,请返回从上到下的折痕的数组,若为下折痕则对应元素为"down",若为上折痕则为"up".
测试样例:
输入: 1
输出:“down”;
刚开始不知道怎么做,后来自己拿纸折了好多次,终于明白了其中的含义,
其实对于纸折的次数与树有关系,也就是说可以使用树中的便利方法来求解:
对折次数:
1
down
2
down down up
3
down down up down down up up
4
down down up down down up up down down down up up down up up
题目中要求是从上到下的折痕的数组,那么就可以使用二叉树的中序遍历序列来列出所有的从上
到下的数组,代码如下:
import java.util.*;
public class FoldPaper {
public String[] foldPaper(int n) {
// write code here
ArrayList<String> list = new ArrayList<String>();
fold(list,1,n,true);
int m=list.size();
String[] put=new String[m];
int i=0;
for(String s:list){
put[i++]=s;
}
return put;
}
public static void fold(ArrayList<String> list,int cut,int n, boolean flag){
if(cut>n){
return ;
}
fold(list,cut+1,n,true);
String in=flag?"down":"up";
list.add(in);
fold(list,cut+1,n,false);
}
}
public class FoldPaper {
public String[] foldPaper(int n) {
// write code here
ArrayList<String> list = new ArrayList<String>();
fold(list,1,n,true);
int m=list.size();
String[] put=new String[m];
int i=0;
for(String s:list){
put[i++]=s;
}
return put;
}
public static void fold(ArrayList<String> list,int cut,int n, boolean flag){
if(cut>n){
return ;
}
fold(list,cut+1,n,true);
String in=flag?"down":"up";
list.add(in);
fold(list,cut+1,n,false);
}
}