Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit64f46bd

Browse files
committed
jump
1 parentf50700c commit64f46bd

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

‎dp/CanJump.java

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
packageAlgorithms.dp;
2+
3+
publicclassCanJump {
4+
publicstaticvoidmain(String[]strs) {
5+
//int[] A = { 2, 2, 3, 4, 5 };
6+
}
7+
8+
// DP1.
9+
publicbooleancanJump1(int[]A) {
10+
if (A ==null ||A.length ==0) {
11+
returnfalse;
12+
}
13+
14+
intlen =A.length;
15+
boolean[]can =newboolean[len];
16+
can[0] =true;
17+
18+
for (inti =1;i <len;i++) {
19+
can[i] =false;
20+
for (intj =0;j <i;j++) {
21+
// j can arrive and can jump to i.
22+
if (can[j] &&A[j] >=i -j) {
23+
can[i] =true;
24+
break;
25+
}
26+
}
27+
}
28+
29+
returncan[len -1];
30+
}
31+
32+
// DP2.
33+
publicbooleancanJump2(int[]A) {
34+
if (A ==null ||A.length ==0) {
35+
returnfalse;
36+
}
37+
38+
intlen =A.length;
39+
40+
for (inti =1;i <len;i++) {
41+
booleancan =false;
42+
for (intj =0;j <i;j++) {
43+
// j can arrive and can jump to i.
44+
if (A[j] >=i -j) {
45+
// 说明i是可达的,置标记位
46+
can =true;
47+
break;
48+
}
49+
}
50+
51+
// 优化:如果某一步已经到不了了,后面的也不必再计算了.
52+
if (!can) {
53+
returnfalse;
54+
}
55+
}
56+
57+
returntrue;
58+
}
59+
60+
// 3. DFS.
61+
publicstaticbooleancanJump3(int[]A) {
62+
if (A ==null ||A.length ==0) {
63+
returnfalse;
64+
}
65+
66+
returncanJump(A,A.length -1);
67+
}
68+
69+
publicstaticbooleancanJump(int[]A,intindex) {
70+
if (index ==0) {
71+
returntrue;
72+
}
73+
74+
for (inti =0;i <=index -1;i++) {
75+
if (A[i] >=index -i) {
76+
returncanJump(A,i);
77+
}
78+
}
79+
80+
returnfalse;
81+
}
82+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp