[M] 55. Jump Game

YJ·3일 전

leetcode

목록 보기
99/100

https://leetcode.com/problems/jump-game

문제

각 발판에서 갈 수 있는 최대 거리 나타낸 배열에서 마지막 칸 도달할 수 있는지

답안

public boolean canJump(int[] nums) {
	boolean[] can = new boolean[nums.length];
	dp[0] = true;

	for (int i = 0; i < nums.length; i++) {
		if (can[i] == false) {
			continue;
		}
		int max = nums[i];
		for (int j = 0; j <= max; j++) {
			if (i + j < nums.length) {
				can[i + j] = true;
			}
		}
	}
	return can[nums.length - 1];
}

메모

갈 수 있는 최대 칸? 만 int 로 관리해주면 된다고 한다. Greedy 하게..

public boolean canJump(int[] nums) {
	int farthest = 0;

	for (int i = 0; i < nums.length; i++) {
		if (i > farthest) {
			return false;
		}

		farthest = Math.max(farthest, i + nums[i]);

		if (farthest >= nums.length - 1) {
			return true;
		}
	}
	return true;
}
profile
Hello

0개의 댓글