점프 게임 리트코드 문제
5427 단어 javadynamicprogrammingleetcode
마지막 인덱스에 도달할 수 있으면 true를 반환하고 그렇지 않으면 false를 반환합니다.
예 1:
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
솔루션: Dp 메모이제이션(하향식 접근 방식)
class Solution {
public boolean canJump(int[] nums) {
// we will solve it using dp
boolean[] dp = new boolean[nums.length];
/*
Fill the dp indices with true , as true will tell us that this
index has not been explored. And if after the exploration this index is still true it will mean that we can reach the last index from current index*/
Arrays.fill(dp,true);
return solve(nums,0,dp);
}
public boolean solve(int[] nums,int index, boolean[] dp){
// base cases
if(index == nums.length-1) return true;
if(index>=nums.length) return false;
if(dp[index]==false) return false; // this means that this index has been explored and it does not lead to the last index
// at given index i we jump to i+1 or i+2 .... till i+k <=i+nums[i];
/*
Example :[2,3,1,1,4]
if i =0, nums[i] = 2
we can jump to i+1 i.e. 0+1 (less than i+nums[i] which is 2) or 0+2 (which is equals to 2) */
for(int i = index+1;i<=index+nums[index];i++){
if(dp[i]){ // traverse only if its true, means its has not been traversed
dp[i] = solve(nums,i,dp);
// even after traversal if it comes as true , it will mean that last index is reachable from this index.
if(dp[i]) return true;
}
}
return false; // return false if the last index is not reachable.
}
}
Reference
이 문제에 관하여(점프 게임 리트코드 문제), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/prashantrmishra/jump-game-leetcode-problem-14bf텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)