题目: 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. Approach #1 Brute Force [Time Limit Ex…
目录 题目链接 注意点 解法 小结 题目链接 Min Cost Climbing Stairs - LeetCode 注意点 注意边界条件 解法 解法一:这道题也是一道dp题.dp[i]表示爬到第i层的最小cost,想要到达第i层只有两种可能性,一个是从第i-2层上直接跳上来,一个是从第i-1层上跳上来.所以可以得到dp[i] = min(dp[i- 2] + cost[i - 2], dp[i - 1] + cost[i - 1]).时间复杂度O(n). class Solution { pu…
目录 题目链接 注意点 解法 小结 题目链接 Climbing Stairs - LeetCode 注意点 注意边界条件 解法 解法一:这道题是一题非常经典的DP题(拥有非常明显的重叠子结构).爬到n阶台阶有两种方法:1. 从n-1阶爬上 2. 从n-2阶爬上.很容易得出递推式:f(n) = f(n-1)+f(n-2)于是可以得到下面这种最简单效率也最低的解法 -- 递归. class Solution { public: int climbStairs(int n) { if(n == 0 |…
1- 问题描述 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? 2- 思路分析 很自然的会想到递归,假设 n 级台阶有 T(n) 种不同走法.最后一步存在两种情况:剩下 1 级台阶,或者,剩下 2 级台阶. 第一种情…
问题描述 Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 和Balanced Binary Tree那题很像.定义T(p)为以p为根的树,T(p) = T(q)需要符合两个条件:…
问题描述: 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? 提示:Dinamic Programming,动态规划,这是个斐波那契数列问题. 方法一: //找规律,设n个台阶的方法数为f(n) //f(1) = 1;…
题目链接 题意 : 求斐波那契数列第n项 很简单一道题, 写它是因为想水一篇博客 勾起了我的回忆 首先, 求斐波那契数列, 一定 不 要 用 递归 ! 依稀记得当年校赛, 我在第一题交了20发超时, 就是因为用了递归, 递归时大量的出入栈操作必然比循环时间来得久 这题估摸着是每个测试样例就一个数, 记忆化的优势显示不出来, 但还是要认真看题 严格要求自己 记忆化搜索 vector<int> dp; int climbStairs(int n) { if (dp.size() <= 2)…
这是悦乐书的第159次更新,第161篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第18题(顺位题号是70).你正在爬楼梯,它需要n步才能达到顶峰.每次你可以爬1或2步,你可以通过多少不同的方式登顶?注意:给定n是一个正整数.例如: 输入:2 输出:2 说明:有两种方法可以爬到顶端 1.1步 + 1步 2.2步 输入:3 输出:3 说明:有三种方法可以爬到顶端 1.1步 + 1步 + 1步 2.1步 + 2步 3.2步 + 1步 输入:4 输出:5 说明:有5种方法…
这是悦乐书的第307次更新,第327篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第176题(顺位题号是746).在楼梯上,第i步有一些非负成本成本[i]分配(0索引).一旦支付了费用,您可以爬一到两步.您需要找到到达楼层顶部的最低成本,您可以从索引为0的步骤开始,也可以从索引为1的步骤开始.例如: 输入:cost= [10,15,20] 输出:15 说明:最便宜的是从成本[1]开始,支付该成本并返回顶部. 输入:cost= [1,100,1,1,1,100,1,1…
1.题目 70. Climbing Stairs——Easy 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:…