正文
## 不推荐 效率极低 ##
def
setpMethod(num)
:
if
(n ==
1
or
n ==
2
):
return
n
else:
return
self
.setpMethod(num-
1
)+
self
.setpMethod(num-
2
)
## 推荐写法 ##
def
climbStairs(
self
, n)
:
if
(n ==
1
or
n ==
2
):
return
n
num1=
1
num2=
2
while
(n >=
3
):
result = num1 + num2
num1 = num2
num2 = result
n -=
1
return
result
## Java ##
public int setpMethod(int n){
if
(n ==
1
||
n ==
2
){
return
n;
}
int result =
0
,n1 =
1
,n2 =
2
;
while
(n>=
3
){
result = n1 + n2;
n1 = n2;
n2 = result;
n--;
}
return
result;
}
题目3:
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。判断你是否能够到达最后一个位置。
示例 1:
输入: [2,3,1,1,4]
输出: true
解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。
示例 2:
输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。
## python ##
class Solution(object):
def canJump(self, nums):
need = 1
if(len(nums) ==1):
return True
if(nums[0] == 0):
return False
for i in range(len(nums)-2,-1,-1):
if(nums[i] == 0 or nums[i] < need):
need += 1
else:
need = 1
if(need == 1) :
return True
else:
return False
## java ##
public boolean canJump(int[] nums) {
int n = 1;
if(nums.length ==1){
return true;
}
if(nums[0] == 0){
return false;
}
for(int i=nums.length-2; i>=0; i--){
if(nums[i] >= n){
n=1;
}else{
n++;
}
}
if(n == 1){
return