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 
    
  • 相关阅读:
    WPF 中英文切换
    System.Data.Entity.Core.ProviderIncompatibleException:0x89c50107
    WinForm使用原生gdi+绘制自定义曲线图、折线图
    C#使用EPPlus读写excel
    ICSharpCode.SharpZipLib C# 压缩文件夹SharpZipHelper
    C# XSLT 转换word 生成word
    代码生成器集合
    优秀的个人博客
    面试经典复习资料
    图解算法
  • 原文地址:https://www.cnblogs.com/kristse/p/12354421.html
Copyright © 2011-2022 走看看