mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 08:16:50 +08:00
Implemented Palindrome Partitioning using Backtracking algorithm (#1591)
* Implemented Palindrome Partitioning using Backtracking algorithm * fix:Updated palindromePartition algorithm * code clean up * Rephrase doc comment & move to appropriate function --------- Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
This commit is contained in:

committed by
GitHub

parent
39d01138ec
commit
1b66d86bd7
30
Recursive/PalindromePartitioning.js
Normal file
30
Recursive/PalindromePartitioning.js
Normal file
@ -0,0 +1,30 @@
|
||||
import { palindrome } from './Palindrome'
|
||||
|
||||
/*
|
||||
* Given a string s, return all possible palindrome partitionings of s.
|
||||
* A palindrome partitioning partitions a string into palindromic substrings.
|
||||
* @see https://www.cs.columbia.edu/~sedwards/classes/2021/4995-fall/proposals/Palindrome.pdf
|
||||
*/
|
||||
const partitionPalindrome = (s) => {
|
||||
const result = []
|
||||
backtrack(s, [], result)
|
||||
return result
|
||||
}
|
||||
|
||||
const backtrack = (s, path, result) => {
|
||||
if (s.length === 0) {
|
||||
result.push([...path])
|
||||
return
|
||||
}
|
||||
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const prefix = s.substring(0, i + 1)
|
||||
if (palindrome(prefix)) {
|
||||
path.push(prefix)
|
||||
backtrack(s.substring(i + 1), path, result)
|
||||
path.pop()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default partitionPalindrome
|
Reference in New Issue
Block a user