zoukankan      html  css  js  c++  java
  • Leetcode之70. Climbing Stairs Easy

    Leetcode 70 Climbing Stairs Easy

    https://leetcode.com/problems/climbing-stairs/

    You are climbing a stair case. It takes n steps to reach to the top.

    Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

    Note: Given n will be a positive integer.

    Example 1:

    Input: 2
    Output: 2
    Explanation: There are two ways to climb to the top.
    1. 1 step + 1 step
    2. 2 steps
    

    Example 2:

    Input: 3
    Output: 3
    Explanation: There are three ways to climb to the top.
    1. 1 step + 1 step + 1 step
    2. 1 step + 2 steps
    3. 2 steps + 1 step

    分析:

    爬台阶这道题印象深刻,为什么呢,tecent春招电话面考我了,但是年幼无知的我语无伦次,只说了用动态规划。当时旁边没有笔、纸,空荡荡的走廊,在这种情境下,怎么做这道题呢?

    首先,逆向思考:要想爬上n_th台阶,那么有两种方式:①(n - 2)_th爬两个台阶;②(n - 1)_th爬一个台阶。也就是ways(n-2) + ways(n-1)即为最后的攀登方式总数。由此可以想到用动规的思想来解这道题。
    其次,正向思考

    • 爬第一个台阶,一种方式—— 1step
    • 爬第二个台阶,两种方式—— 1step+1step 或 2step
    • 爬第三个台阶,想一下怎么利用前两个结果?哈哈,不就是2 + 1吗?!这样话,问题就迎刃而解,对得起Easy这个难度。
    class Solution {
    public:
        int climbStairs(int n) {
            int preTwoStep = 1;
            int preOneStep = 2;
            int ways = 0;
            if (n == 1 || n == 2)
                return n == 1 ? 1 : 2;
            else {
                for (int i = 3; i <= n; ++i) {
                    ways = preTwoStep + preOneStep;
                    preTwoStep = preOneStep;
                    preOneStep = ways;
                }
            }
            return ways;
        }
    };

    这道题可能在有纸或现场面试的情况下,即使当时比现在更菜,但做出来的概率应该还是很大的,但无奈是电话面试。但是,现在的我并不这么想。这道题是第70题,没有说是某300或500,并且还是一道easy,面试官对我已经很仁慈了;即使这样,我依然做不出来,甚至没有思路,说明我根本没刷到这道题,足以说明我刷题这方面能力欠缺,如果我是面试官,我也不敢要。这告诫我,如果你真的很重视面试,如果你真的想拿offer,那么就不要限于想,就是干!希望在努力的你也一样!

  • 相关阅读:
    WPF 使用 Direct2D1 画图 绘制基本图形
    WPF 使用 Direct2D1 画图 绘制基本图形
    dot net core 使用 IPC 进程通信
    dot net core 使用 IPC 进程通信
    win2d 图片水印
    win2d 图片水印
    Java实现 LeetCode 240 搜索二维矩阵 II(二)
    PHP closedir() 函数
    PHP chroot() 函数
    PHP chdir() 函数
  • 原文地址:https://www.cnblogs.com/Flash-ylf/p/11074418.html
Copyright © 2011-2022 走看看