Leet Code OJ 70. Climbing Stairs [Difficulty: 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?
翻译:
你在爬一个楼梯。到达顶部有n级阶梯。
每次你可以选择爬一级或者二级。在多少不同的方式去到达顶部?
分析:
当n=1,无疑只有一种方式,s=1。
n=2,s=2。
n=3,s=3。
n=4,s=5。
我们发现这个实际是一个斐波那契数列。第一反应是递归实现,f(n)=f(n-1)+f(n-2),但是递归实现,有多次重复计算,比如在计算f(n-1)时,需要使用f(n-2)+f(n-3),但是这个时候另一个递归调用已经去算了f(n-2),相当于f(n-2)被计算了2次,这种重复计算的情况普遍存在,将会浪费大量计算时间。很自然的想到反过来操作,递归是从目标算到基础值,而我们可以采用迭代从基础值1,2累加上去。
代码1(递归):
public class Solution {public int climbStairs(int n) {if(n==1||n==2){return n;}else{return climbStairs(n-2)+climbStairs(n-1);}}
}
代码2(迭代):
public class Solution {public int climbStairs(int n) {if(n==1||n==2){return n;}int n1=1;int n2=2;for(int i=3;i<=n;i++){int temp=n1+n2;n1=n2;n2=temp;}return n2;}
}
Leet Code OJ 70. Climbing Stairs [Difficulty: Easy]相关推荐
- Leet Code OJ 112. Path Sum [Difficulty: Easy]
题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...
- Leet Code OJ 344. Reverse String [Difficulty: Easy]
题目: Write a function that takes a string as input and returns the string reversed. Example: Given s ...
- Leet Code OJ 28. Implement strStr() [Difficulty: Easy]
题目: Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if ne ...
- Leet Code OJ 125. Valid Palindrome [Difficulty: Easy]
题目: Given a string, determine if it is a palindrome, considering only alphanumeric characters and ig ...
- Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]
题目: Given a string containing just the characters , determine if the input string is valid. The brac ...
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...
- Leet Code OJ 223. Rectangle Area [Difficulty: Easy]
题目: Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle is defin ...
- Leet Code OJ 189. Rotate Array [Difficulty: Easy]
题目: Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the ar ...
- Leet Code OJ 66. Plus One [Difficulty: Easy]
题目: Given a non-negative number represented as an array of digits, plus one to the number. The digit ...
最新文章
- C# 使用正则表达式去掉字符串中的数字
- java线程系列---condition的讲解
- SUBMIT 的使用方法
- ESXI主机的Management网络管理了什么?
- Linux设备驱动之字符设备(一)
- Activation function in Neural Network
- Android Studio R类找不到(Mac)
- easychm生成帮助文件时出现的目录导航乱码问题
- 《深度学习》读后感作文3100字
- 七大人脉宝典造亿万富翁
- Virtual Box报错VT-x is not available (VERR_VMX_NO_VMX)--大踩坑(二)
- 如何在Windows 10中打开设置?
- Arduino智能小车设计(一)
- 项目过程管理(十八)集体加班制度
- ASP.NET访问Excel 失败的解决方法(错误号:80070005,8000401a)
- 堆和栈的区别(内存和数据结构)
- 计算机表格判断是否合格操作,关于一些刚开始接触计算机的基础知识(2)
- git 忽视修改过的文件
- HashMap面试题,看这一篇就够了!
- python键盘监听及模拟键盘输入keyboard