关关的刷题日记68 – Leetcode 70 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.
Input: 3 Output: 3 Explanation: There are three ways to climb to the top.
题目的意思是爬楼梯,楼梯一共有n个台阶。每次可以爬一个台阶或者两个台阶,问爬到楼顶一共有多少种方式。
思路:动态规划的题目:假设爬到第i个楼梯一共有re[i]种方式,则状态转移方程re[i]= re[i-1]+ re[i-2],即爬到第i个楼梯可以是从第i-1个楼梯,爬一步上来的,也可以是从第i-2个楼梯爬两步上来。
class Solution {public:
int climbStairs(int n) {
if(n<=2)
return n;
int temp1=1, temp2=2, re;
for(int i=3; i<=n; i++)
{
re=temp1+temp2;
temp1=temp2;
temp2=re;
}
return re;
}};
以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。