26 Nov 2016

# Recursion to greedy

Author: derek0883@gmail.com

This example will show you how to use recursion method solve problem, then easily lead to greedy solution. For basic graph concept. Here is very good material: http://algs4.cs.princeton.edu/40graphs/

## Jump Game II

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

Note: You can assume that you can always reach the last index.

### BFS O(n^2) time complexity

start from index 0, each step we have nums[i] options.

``````public int bfs(int[] nums) {
if (nums == null || nums.length == 0)
return 0;
Queue<Integer> q = new LinkedList<>();
boolean[] marked = new boolean[nums.length];
int step = 0;
q.offer(0);
while (!q.isEmpty()) {
int n = q.size();
while (n-- != 0) {
int m = q.poll();
if (m >= nums.length-1)
return step;
marked[m] = true;
for (int i = 1; i <= nums[m]; i++) {
if (m+i < nums.length && !marked[m+i])
q.offer(m+i);
}
}
step++;
}
return step;
}
``````

### Greedy O(n) time complexity

``````private int greedy(int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int steps = 0;
int max = nums[0];
int cur = 0;
int n = nums.length;

for (int i = 0; i < n && cur < n-1; i++) {
if (cur < i) {
cur = max;
steps++;
}
max = Math.max(max, nums[i]+i);
}
return steps;
}
``````