Partition a string s so that every substring of the partition is a palindrome. Return all possible palindrome partitionings.
Precompute pal[i][j] = (s[i] = s[j]) and pal[i+1][j−1], so every palindrome check during the backtracking is a table lookup.
1function partition(s: string): string[][] {2const n = s.length, pal = Array.from({ length: n }, () => new Array(n).fill(false));3for (let i = n - 1; i >= 0; i--)4for (let j = i; j < n; j++)5pal[i][j] = s[i] === s[j] && (j - i < 2 || pal[i + 1][j - 1]);6const res: string[][] = [], path: string[] = [];7function dfs(start: number) {8if (start === n) { res.push([...path]); return; }9for (let end = start; end < n; end++)10if (pal[start][end]) {11path.push(s.slice(start, end + 1)); dfs(end + 1); path.pop();12}13}14dfs(0);15return res;16}
| 0:a | 1:a | 2:b | 3:b | |
|---|---|---|---|---|
| 0:a | ||||
| 1:a | ||||
| 2:b | ||||
| 3:b | T |
pal[3][3] ("b") = true.
Space: play/pause · ←/→: step