美文网首页
【LintCode 题解】842. 【中等】折纸

【LintCode 题解】842. 【中等】折纸

作者: Downstream | 来源:发表于2018-03-11 17:23 被阅读0次
  • 难度:中等
  • Microsoft 面试题

题目

折纸,每次都是将纸从右向左对折,凹痕为 0,凸痕为 1,求折 n 次后,将纸展开的折痕组成的 01 序列。

注意事项

  • 1 ≤ n ≤ 20

样例

Sample Input:
1

Sample Output:
"0"
Sample Input:
1

Sample Output:
"001"

解答

可以容易写出前 4 项的 01 序列:

              0
      0       0       1
  0   0   1   0   0   1   1
0 0 1 0 0 1 1 0 0 0 1 1 0 1 1

可以看到其中的规律:

  1. 第 1 条折痕总为 0
  2. 之后每次在新产生的折痕两侧产生一个凹折痕和一个凸折痕

于是这个序列可以看成是以下二叉树中序遍历的结果:

  1. 根结点的值为 0
  2. 每个节点的左子树的根结点值恒为 0,右子树的的根结点的值为 1。

代码如下:

class Solution 
{
private:
    class TreeNode 
    {
    public:
        char val;
        TreeNode *left, *right;
        TreeNode(char val, TreeNode *left = nullptr, TreeNode *right = nullptr)
            : val(val), left(left), right(right) {}
    };

    string result;

    void midOrderTraverse(TreeNode *root) 
    {
        if(root != nullptr) 
        {
            midOrderTraverse(root->left);
            result += root->val;
            midOrderTraverse(root->right);
        }
    }

    void buildTree(TreeNode *root, int n) 
    {
        root->left = new TreeNode('0');
        root->right = new TreeNode('1');
        if(n == 1)
            return;
        else 
        {
            buildTree(root->left, n - 1);
            buildTree(root->right, n - 1);
        }
    }
public:
    /**
     * @param n: The folding times
     * @return: the 01 string
     */
    string getString(int n) 
    {
        TreeNode *root = new TreeNode('0');
        if(n != 1)
            buildTree(root, n - 1);
        midOrderTraverse(root);
        return result;
    }
};

相关文章

  • 【LintCode 题解】842. 【中等】折纸

    难度:中等 Microsoft 面试题 题目 折纸,每次都是将纸从右向左对折,凹痕为 0,凸痕为 1,求折 n 次...

  • 【LintCode 题解】819. 【中等】单词排序

    难度:中等 Facebook 面试题 题目 给一个新的字母表,如 {c, b, a, d, e, f, g, h,...

  • 【LintCode 题解】808. 【中等】影际网络

    难度:中等 标签:优先队列、二叉查找树、深度优先搜索 Amazon 面试题 题目 给一些 movie(编号从 0 ...

  • 第k大元素

    (lintcode上面的题解)第k大元素:(从小到大的排序)

  • [leetcode/lintcode 题解] 解码字符串 ·

    leetcode/lintcode 题解] 解码字符串 · Decode String 【题目描述】 给出一个表...

  • LintCode - 旋转链表(中等)

    版权声明:本文为博主原创文章,未经博主允许不得转载。 难度:中等 要求: 给定一个链表,旋转链表,使得每个节点向右...

  • lintCode题解 (1)

    标签(空格分隔): lintCode 题目: 给出两个数A,B 在不使用加法运算的符的情况下,计算 A与B的和 输...

  • lintCode题解(8)

    标签(空格分隔): lintCode 旋转字符串 给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)...

  • lintCode题解(2)

    标签(空格分隔): lintCode 题目: 尾部的零 描述: 设计一个算法,计算出n的阶乘中尾部零的个数 样例 ...

  • lintCode题解(9)

    标签(空格分隔): lintCode Fizz Buzz 问题 描述: 给你一个整数n. 从 1 到 n 按照下面...

网友评论

      本文标题:【LintCode 题解】842. 【中等】折纸

      本文链接:https://www.haomeiwen.com/subject/neywfftx.html