/**
* @param {string} s
* @return {string[][]}
*/
var partition = function (s) {
const palindromeStrCache = new Map();
const isPalindromeStr = (str, start, end) => {
const key = `${start},${end}`;
if (palindromeStrCache.has(key)) {
return palindromeStrCache.get(key);
}
if (start >= end) {
palindromeStrCache.set(key, true);
} else if (str[start] === str[end]) {
// 基于 DP 的计算是否是 Palindrome
palindromeStrCache.set(key, isPalindromeStr(str, start + 1, end - 1));
} else {
palindromeStrCache.set(key, false);
}
return palindromeStrCache.get(key);
};
const dfs = (startIndex, curPath, result) => {
const strLen = s.length;
if (startIndex < strLen) {
for (let endIndex = startIndex; endIndex < strLen; ++endIndex) {
if (isPalindromeStr(s, startIndex, endIndex)) {
curPath.push(s.slice(startIndex, endIndex + 1));
// 执行具体的逻辑
dfs(endIndex + 1, curPath, result);
// 回溯
curPath.pop();
}
}
} else {
// 达到终点,加入最终结果
result.push(curPath.slice());
}
return result;
};
return dfs(0, [], []);
};