[leetcode]有关跳台阶的题

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?

思路:
采用的是动态规划,定义一个长度为n+2的int类型数组result[],每个元素记录的是到达该距离有几种方式。先初始化数result[0]和result[1]为1,因为从起点起跳,只一步就可以到达这两个距离。然后开始遍历该数组,当遍历到距离i时,要去修改数组result[i+1]和result[i+2]中的内容。最后返回result[n],即为结果。

代码:

public class Solution {
    public int climbStairs(int n) {
        int[] result=new int[n+2];
        result[0]=1;
        result[1]=1;
        for(int i=0;i<n;i++){
            if(result[i]>0){
                result[i+1]=result[i+1]+result[i];
                result[i+2]=result[i+2]+result[i];
            }
        }
        return result[n-1];
    }
}

2.数组中给出当前可跳的最大步数,问是否能跳到最后
问题描述:
Given an array of non-negative integers, you are initially positioned at the first index of the array.Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.

For example:
A =[2,3,1,1,4], return true.
A =[3,2,1,0,4], return false.

思路:
定义一个长度n为A.length的布尔类型的数组result[],数组中的元素记录该距离是否可达。初始化result[0]为true。然后遍历该数组,当遇到一元素i为true时,获取A[i]中的值,即在位置i可跳的最远距离t,说明在位置i的下一跳可以跳到i+1~i+t任意一位置,将result数组中的这些位置更新为true。如此遍历,最终返回数组的最后一个值,即为结果

代码:

//代码定义了一个int类型数组,1表示可达,同布尔类型相同
public class Solution {
    public boolean canJump(int[] A) {
        int n=A.length;
        if(n==1)
            return true;
        int[] result=new int[n];
        result[0]=1;
        for(int i=0;i<n;i++){
            if(result[i]==1){
                for(int j=i+1;j<=i+A[i]&&j<n;j++){
                    if(result[j]!=1)
                        result[j]=1;
                }
            }
        }
        if(result[n-1]==1){
            return true;
        }
        return false;
    }
}

3.数组给出当前可跳的最大步数,问跳到最后需要的最小步数
问题描述:
Given an array of non-negative integers, you are initially positioned at the first index of the array.Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A =[2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

思路:
定义一个长度n为A.length的数组result[],每一元素记录跳到该步的最小步数。先初始化数组中的每一元素为最大值,result[0]=0。遍历数组,当遍历到i时,获得A[i]的值为t,则需要更新result i+1~i+t中的内容,判断经过i跳到这点的距离是否小于不经过i到达该点的距离,若小于则需要修改其中的内容为result[i]+1。遍历过后,返回数组的最后一个元素,既可以获得答案。

代码:

扫描二维码关注公众号,回复: 3939935 查看本文章
public class Solution {
    public int jump(int[] A) {
        int[] num=new int[A.length];
        num[0]=0;
        for(int i=1;i<A.length;i++){
            num[i]=Integer.MAX_VALUE;
        }
        for(int i=0;i<A.length;i++){
            for(int j=i+1;j<=i+A[i]&&j<A.length;j++){
                num[j]=Math.min(num[j],num[i]+1);
            }
        }
        return num[A.length-1];
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41618373/article/details/83717098
今日推荐