程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode 44 Jump Game II

LeetCode 44 Jump Game II

編輯:C++入門知識

LeetCode 44 Jump Game II


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

思路:使用遞歸,始終去尋找最小的i能到目標位置。

class Counter {
	public static int counter;
}

public class Solution {
	public int jump(int[] A) {
		Counter.counter = 0;
		return jump(A, A.length - 1);
	}

	private int jump(int[] A, int end) {
		int i = 0;
		for (; i < end; i++) {
			if (i + A[i] >= end) {
				Counter.counter++;
				break;
			}
		}
		if (i == 0)
			return Counter.counter;
		jump(A, i);
		return Counter.counter;
	}
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved