-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path131. Palindrome Partitioning
More file actions
60 lines (42 loc) · 1.26 KB
/
131. Palindrome Partitioning
File metadata and controls
60 lines (42 loc) · 1.26 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
class Solution {
public List<List<String>> partition(String s)
{
int n = s.length();
boolean[][] dp = new boolean[n][n];
for(int i = 0; i < n; i++)
{
dp[i][i] = true;
}
for (int length = 2; length <= n; length++)
{
for (int i = 0; i <= n - length; i++)
{
int j = i + length - 1;
if (s.charAt(i) == s.charAt(j) && (length == 2 || dp[i + 1][j - 1]))
{
dp[i][j] = true;
}
}
}
List<List<String>> result = new ArrayList<>();
backtrack(s, 0, new ArrayList<>(), result, dp);
return result;
}
public void backtrack(String s, int start, List<String> path, List<List<String>> result, boolean[][] dp)
{
if (start == s.length())
{
result.add(new ArrayList<>(path));
return;
}
for (int end = start; end < s.length(); end++)
{
if (dp[start][end])
{
path.add(s.substring(start, end + 1));
backtrack(s, end + 1, path, result, dp);
path.remove(path.size() - 1);
}
}
}
}