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
| class Solution { int[][] f; List<List<String>> ans = new ArrayList<>(); List<String> path = new ArrayList<>(); String s; int n;
public List<List<String>> partition(String s) { this.s = s; n = s.length(); f = new int[n][n]; dfs(0); return ans; }
public void dfs(int i) { if (i == n) { ans.add(new ArrayList<>(path)); return; } for (int j = i; j < n; ++j) { if (isPalindrome(i, j) == 1) { path.add(s.substring(i, j + 1)); dfs(j + 1); path.remove(path.size() - 1); } } }
private int isPalindrome(int i, int j) { if (f[i][j] != 0) return f[i][j];
if (i >= j) f[i][j] = 1; else if (s.charAt(i) == s.charAt(j)) f[i][j] = isPalindrome(i + 1, j - 1); else f[i][j] = -1;
return f[i][j]; } }
|