zoukankan      html  css  js  c++  java
  • 非常经典的面试题,方案很多,一起交流学习

    楼上走到楼下共有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();
            }

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

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

  • 相关阅读:
    [LEETCODE] 初级算法/数组 1.1删除排序数组中的重复项
    [LeetCode]1.Two Sum 两数之和&&第一次刷题感想
    Panda的学习之路(3)——pandas 设置特定的值&处理没有数据的部分
    Panda的学习之路(2)——pandas选择数据
    Panda的学习之路(1)——series 和 Dataframe
    NUMPY的学习之路(2)——索引,合并,分割,赋值
    numpy的学习之路(1)——创建数组以及基本运算
    SpringBoot外部配置夹加载顺序
    SpringBoot2.0官方文档的位置
    @RestController注解
  • 原文地址:https://www.cnblogs.com/luoyuhao/p/7236533.html
Copyright © 2011-2022 走看看