• 非常经典的面试题,方案很多,一起交流学习


    楼上走到楼下共有10个台阶,每一步有3种走法:走1个台阶;走2个台阶;走3个台阶.问可走多少种方案?

    分析

    这个题用排列组合不好作,无法确定步骤,我提供一种方法,供大家参考借鉴:
    不妨设有n阶台阶,既然一次只能走一步或2步或3步,那么假设现在仅剩下最后一步要走,
    有三种情况:
    一 只需要走一步,这时已经走了(n-1)阶,走法与走n-1阶相同,有f(n-1)阶走法;
    二 只需要走两步,同上分析有f(n-2);
    三 只需要走三步,有f(n-3);
    所以走n阶台阶有f(n)=f(n-1)+f(n-2)+f(n-3)种走法;
    很明显,走1阶台阶有1种方法;
    走2阶有两种走法;
    走3阶有4种走法,如下:1 1 1 1 2 2 1 3;
    所以我列出总台阶数与走法的对应表:
    1 2 3 4 5 6 7 8 9 10
    1 2 4 7 13 24 44 81 149 274
    所以有274种走法,是不是不可思议啊

    C语言写法

    if(n==1)
        return 1;
    else if(n==2)
        return 2;
    else if(n==3)
        return 4;
    else
        return f(n-1)+f(n-2)+f(n-3);

     我的写法一

            static void Main(string[] args)
            {
                int x = run(10);
                Console.WriteLine(x);
                Console.ReadKey();
            }
    
            static int run(int x)
            {
                if (x == 1)
                {
                    return 1;
                }
                else if (x == 2)
                {
                    return 2;
                }
                else if (x == 3)
                {
                    return 4;
                }
                else
                {
                    return run(x - 1) + run(x - 2) + run(x - 3);
                }
            }

      我的写法二

            static void Main(string[] args)
            {
                List<int> list = new List<int>() { 1, 2, 4 };
                for (int i = 3; i < 10; i++)
                {
                    int count = list.Sum();
                    list.RemoveAt(0);//删除第一个
                    list.Add(count);//增加相加的和
                    Console.WriteLine(list[2]);
                }
                Console.ReadKey();
            }

     我的写法三

            static void Main(string[] args)
            {
                int[] count = new int[] { 1, 2, 4 };
                for (int i = 4; i < 11; i++)
                {
                    int sum = count.Sum();//求和
                    count[(i - 1) % 3] = sum;//取3的摸
                    Console.WriteLine(sum);
                }
                Console.ReadKey();
            }

      请问下各位高手有没有更优化的写法,一起探讨学习交流下。。。觉得还是挺有意思的题目。

      第三种方案可能是最优的写法了,但很多人可能一下子想不到。。。

  • 相关阅读:
    开始用博客
    nginx 移动端和PC端相互访问
    call、apply、bind的区别
    获取两个日期之间的所有日期组合
    高频前端开发问题
    图片懒加载实现
    某某公司中级前端面试题
    flex 布局
    plupload.js+php批量上传文件到阿里云oss
    H5 iframe 高度-根据内容的高度自适应 / iframe高度适配
  • 原文地址:https://www.cnblogs.com/luoyuhao/p/7236533.html
Copyright © 2020-2023  润新知