const isPalindrome = (s) => s === s.split('').reverse().join('');
var partition = function (s) {
const result = [];
const backTracking = (path, index) => {
if (index === s.length) result.push([...path]);
for (let i = index + 1; i <= s.length; i++) {
let subStr = s.slice(index, i);
if (isPalindrome(subStr)) {
path.push(subStr);
backTracking(path, i);
path.pop();
}
}
};
backTracking([], 0);
return result;
};
這題用回溯法解題,要想到遞迴的中止條件有兩個:
概念圖:
時間複雜度: O(2^n * n)
,n 的部分精確來說是 3 * n,判斷字串是否是回文
空間複雜度: O(n)
Palindrome Partitioning - Backtracking - Leetcode 131