LeetCode 刷题【131. 分割回文串】
131. 分割回文串

自己做
解:递归分割

class Solution {private List<List<String>> res = new ArrayList();public void Travel(String s, int begin, List<String> combinaiton){if(begin == s.length()) //遍历结束res.add(new ArrayList(combinaiton));for(int i = begin; i < s.length(); i++){//判断begin到i是否为回文串boolean is_partition = true;for(int j = begin, z = i; j < z; j++, z--)if(s.charAt(j) != s.charAt(z))is_partition = false;//是回文串,往下继续划分if(is_partition){combinaiton.add(s.substring(begin, i + 1));Travel(s, i + 1, combinaiton);combinaiton.remove(combinaiton.size() - 1);}}}public List<List<String>> partition(String s) {Travel(s, 0, new ArrayList());return res;}
}

看题解

官方题解
class Solution {boolean[][] f;List<List<String>> ret = new ArrayList<List<String>>();List<String> ans = new ArrayList<String>();int n;public List<List<String>> partition(String s) {n = s.length();f = new boolean[n][n];for (int i = 0; i < n; ++i) {Arrays.fill(f[i], true);}for (int i = n - 1; i >= 0; --i) {for (int j = i + 1; j < n; ++j) {f[i][j] = (s.charAt(i) == s.charAt(j)) && f[i + 1][j - 1];}}dfs(s, 0);return ret;}public void dfs(String s, int i) {if (i == n) {ret.add(new ArrayList<String>(ans));return;}for (int j = i; j < n; ++j) {if (f[i][j]) {ans.add(s.substring(i, j + 1));dfs(s, j + 1);ans.remove(ans.size() - 1);}}}
}
