Jump Game II

来源:互联网 发布:json rpc restful 编辑:程序博客网 时间:2024/06/05 09:23

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.)

代码一:dfs,即迭代,小数据可以,大数据会因为迭代太深而超时。

public static void dfs(int[] A, List<Integer> step, int jump, int start, int end){if(start == end){step.add(jump);return;}else if(start > end)return;else{if(start < end){for(int i = 1; i <= A[start]; i++)dfs(A, step, jump + 1, start + i, end);}}}public static int jump(int[] A) {        List<Integer> result = new ArrayList<Integer>();        dfs(A, result, 0, 0, A.length - 1);        int min = result.get(0);        for(int i = 1; i < result.size(); i++)        if(min > result.get(i))        min = result.get(i);        return min;    }
个人理解:涉及到层次即回溯的,可以考虑到dfs,算法不好,努力学习中。

代码二:动态规划。dp[i]代表跳到下标i的位置最少的步数。

dp[0] = 0;

dp[i]: 从位置0~ j~ i - 1中,若d[j] + j >= i, d[i] = d[j] + 1;

public static int jump2(int[] A) {int length = A.length;if(A.length <= 1)return 0;int[] dp = new int[length];dp[0] = 0;for(int i = 1; i < length; i++){for(int j = 0; j < i; j++){if(j + A[j] >= i){dp[i] = dp[j] + 1;break;}}}return dp[length - 1];}



0 0
原创粉丝点击