-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFrogJump.java
More file actions
83 lines (76 loc) · 2.96 KB
/
Copy pathFrogJump.java
File metadata and controls
83 lines (76 loc) · 2.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//一只青蛙想要过河。 假定河流被等分为 x 个单元格,并且在每一个单元格内都有可能放有一石子(也有可能没有)。 青蛙可以跳上石头,但是不可以跳入水中。
//
// 给定石子的位置列表(用单元格序号升序表示), 请判定青蛙能否成功过河(即能否在最后一步跳至最后一个石子上)。 开始时, 青蛙默认已站在第一个石子上,并可以
//假定它第一步只能跳跃一个单位(即只能从单元格1跳至单元格2)。
//
// 如果青蛙上一步跳跃了 k 个单位,那么它接下来的跳跃距离只能选择为 k - 1、k 或 k + 1个单位。 另请注意,青蛙只能向前方(终点的方向)跳跃。
//
//
// 请注意:
//
//
// 石子的数量 ≥ 2 且 < 1100;
// 每一个石子的位置序号都是一个非负整数,且其 < 231;
// 第一个石子的位置永远是0。
//
//
// 示例 1:
//
//
//[0,1,3,5,6,8,12,17]
//
//总共有8个石子。
//第一个石子处于序号为0的单元格的位置, 第二个石子处于序号为1的单元格的位置,
//第三个石子在序号为3的单元格的位置, 以此定义整个数组...
//最后一个石子处于序号为17的单元格的位置。
//
//返回 true。即青蛙可以成功过河,按照如下方案跳跃:
//跳1个单位到第2块石子, 然后跳2个单位到第3块石子, 接着
//跳2个单位到第4块石子, 然后跳3个单位到第6块石子,
//跳4个单位到第7块石子, 最后,跳5个单位到第8个石子(即最后一块石子)。
//
//
// 示例 2:
//
//
//[0,1,2,3,4,8,9,11]
//
//返回 false。青蛙没有办法过河。
//这是因为第5和第6个石子之间的间距太大,没有可选的方案供青蛙跳跃过去。
//
// Related Topics 动态规划
// 👍 102 👎 0
package leetcode.editor.cn;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* [403]青蛙过河
*/
public class FrogJump {
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean canCross(int[] stones) {
int len = stones.length;
Map<Integer, Set<Integer>> dp = new HashMap<>();
for(int i = 0; i < len; i++)
dp.put(stones[i], new HashSet<>());
dp.get(stones[0]).add(0);
for(int i = 0; i < len; i++) {
Set<Integer> set = dp.get(stones[i]);
for(int step : set) {
for(int k = step - 1; k <= step + 1; k++) {
if(k > 0 && dp.containsKey(stones[i] + k))
dp.get(stones[i] + k).add(k);
}
}
}
return !dp.get(stones[len - 1]).isEmpty();
}
}
//leetcode submit region end(Prohibit modification and deletion)
public static void main(String[] args) {
Solution solution = new FrogJump().new Solution();
}
}