请把纸条竖着放在桌⼦上,然后从纸条的下边向上⽅对折,压出折痕后再展 开。此时有1条折痕,突起的⽅向指向纸条的背⾯,这条折痕叫做“下”折痕 ;突起的⽅向指向纸条正⾯的折痕叫做“上”折痕。如果每次都从下边向上⽅ 对折,对折N次。请从上到下计算出所有折痕的⽅向。
给定折的次数n,请返回从上到下的折痕的数组,若为下折痕则对应元素为"down",若为上折痕则为"up".
测试样例:
输入:1
输出:down
采用递归进行计算,每一次折纸,上面位置必定为下,然后和上一次折纸的位置对应处一定为下,即折纸朝向以上一次折纸的位置相互对称,所以进行递归即可,可先采用int数组,down设为-1,up设置为+1。
具体代码如下:
public class FoldPaper { public String[] foldPaper(int n) { int length = (int) (Math.pow(2, n) - 1);//总折纸长度 int[] result = new int[length]; getIt(0, n, result); String[] strings = new String[length]; for(int i = 0; i < length; i++){ if(result[i] == -1) strings[i] = "down"; else strings[i] = "up"; } return strings; } public void getIt(int index,int n, int[] result) { if(n >= 1){ result[index] = -1; int newindex = index * 2 + 1; //下一次折纸位置 for(int i = 1; i <= index; i++){ result[index + i] = -result[index - i];//以折纸位置对称 } getIt(newindex, n-1, result); } } }