题目地址: 链接
思路: 依然是简单的递归回溯(枚举所有组合,逐个检查组合中的每个字符串是否为回文串)
js
/**
* @param {string} s
* @return {string[][]}
*/
let isP = (arr) => {
for(let str of arr) {
let n = str.length;
let m = Math.floor(str.length / 2);
for(let i = 0; i < m; i ++) {
if(str[i] !== str[n - 1 - i]) {
return false;
}
}
}
return true;
}
var partition = function(s) {
let ans = [];
let n = s.length;
const dfs = (idx, arr) => {
if(idx == n) {
ans = [...arr];
return;
}
let arrLen = arr.length;
for(let i = 0; i < arrLen; i ++) {
let subarr = arr[i];
arr.push([...subarr, s[idx]]);
let m = subarr.length;
subarr[m - 1] += s[idx];
}
if(arr.length == 0) arr.push([s[idx]]);
dfs(idx + 1, arr);
}
dfs(0, [])
let res = [];
for(const subAns of ans) {
if(isP(subAns)) res.push(subAns);
}
return res;
};