zoukankan      html  css  js  c++  java
  • [算法]折纸问题

    题目

    请把一段纸条竖着放在桌子上,然后从纸条的下边向上方对折1次,压出折痕后展开。此时 折痕是凹下去的,即折痕突起的方向指向纸条的背面。如果从纸条的下边向上方连续对折2 次,压出折痕后展开,此时有三条折痕,从上到下依次是下折痕、下折痕和上折痕。
    给定一 个输入参数N,代表纸条都从下边向上方连续对折N次,请从上到下打印所有折痕的方向。 例如:N=1时,打印: down ;N=2时,打印: down down up

    解答

    本质上就是将下面这棵二叉树按照 右 -> 中 -> 左 的顺序进行遍历;

    package nowcoder.easy.day04;  
      
    /**  
     * 折纸问题 
     * @author GJXAIOU  
     * 将一棵头结点为 down,然后左孩子为 down,右孩子为 up 的二叉树按照 右、中、左顺序打印即可。 
     */
     public class PaperFolding {  
      
        public static void printAllFolds(int flodTime) {  
            printProcess(1, flodTime, true);  
        }  
      
        public static void printProcess(int i, int flodTime, boolean down) {  
            if (i > flodTime) {  
                return;  
            }  
            printProcess(i + 1, flodTime, true);  
            System.out.print(down ? "down " : "up ");  
            printProcess(i + 1, flodTime, false);  
        }  
      
        public static void main(String[] args) {  
            int N = 1;  
            printAllFolds(N);  
          System.out.println();  
            printAllFolds(2);  
          System.out.println();  
            printAllFolds(3);  
          System.out.println();  
            printAllFolds(4);  
        }  
    }
    

    程序运行结果

    down 
    down down up 
    down down up down down up up 
    down down up down down up up down down down up up down up up 
    
  • 相关阅读:
    java01 java基础知识
    01 开发准备 启动PHP服务与环境配置
    Axure 9.0 使用教程2-函数分类
    Axure 9.0 使用教程1-软件概述
    Python 字符串 列表 元组 字典 集合学习总结
    Python 函数定义 调用 迭代器 生成器 递归和推导式
    Python习题
    Python 条件 循环 及其他语句
    Python 字典
    Python 字符串
  • 原文地址:https://www.cnblogs.com/kristse/p/12354421.html
Copyright © 2011-2022 走看看