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

Commit5f4d6e3

Browse files
committed
dp
1 parent53d3782 commit5f4d6e3

File tree

1 file changed

+54
-4
lines changed

1 file changed

+54
-4
lines changed

‎dfs/Partition.java

Lines changed: 54 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
importjava.util.List;
66

77
publicclassPartition {
8-
publicList<List<String>>partition(Strings) {
8+
publicList<List<String>>partition1(Strings) {
99
List<List<String>>ret =newArrayList<List<String>>();
1010
List<String>path =newArrayList<String>();
1111

@@ -64,13 +64,63 @@ public void dfs(String s, List<String> path, List<List<String>> ret, int index,
6464
path.remove(path.size() -1);
6565
}
6666
}
67+
68+
publicList<List<String>>partition(Strings) {
69+
List<List<String>>ret =newArrayList<List<String>>();
70+
List<String>path =newArrayList<String>();
71+
72+
if (s ==null) {
73+
returnret;
74+
}
75+
76+
boolean[][]isPalindrom =buildPalindromDP(s);
77+
78+
dfs2(s,path,ret,0,isPalindrom);
79+
80+
returnret;
81+
}
6782

6883
/*
6984
* Solution 2: Use DP to reduce the duplicate count.
7085
* */
71-
boolean[][]isPalindromDP(Strings) {
86+
boolean[][]buildPalindromDP(Strings) {
7287
intlen =s.length();
73-
boolean[][]ret =newboolean[len][len];
88+
boolean[][]D =newboolean[len][len];
89+
90+
for (intj =0;j <len;j++) {
91+
for (inti =0;i <=j;i++) {
92+
if (j ==0) {
93+
D[i][j] =true;
94+
continue;
95+
}
96+
97+
// 注意,这里要加上j - i <= 2否则会越界
98+
D[i][j] =s.charAt(i) ==s.charAt(j)
99+
&& (j -i <=2 ||D[i +1][j -1]);
100+
}
101+
}
102+
103+
returnD;
104+
}
105+
106+
/*
107+
we use a map to store the solutions to reduce the times of computing.
108+
*/
109+
publicvoiddfs2(Strings,List<String>path,List<List<String>>ret,intindex,boolean[][]isPalindromDP) {
110+
if (index ==s.length()) {
111+
ret.add(newArrayList<String>(path));
112+
return;
113+
}
114+
115+
for (inti =index;i <s.length();i++) {
116+
Stringsub =s.substring(index,i +1);
117+
if (!isPalindromDP[index][i]) {
118+
continue;
119+
}
120+
121+
path.add(sub);
122+
dfs2(s,path,ret,i +1,isPalindromDP);
123+
path.remove(path.size() -1);
124+
}
74125
}
75-
76126
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp