#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
// Check if substring s[left..right] is palindrome
bool isPalindrome(char *s, int left, int right) {
while (left < right) {
if (s[left] != s[right]) return false;
left++;
right--;
}
return true;
}
// Structure to hold one partition
typedef struct {
char **parts;
int size;
int capacity;
} Partition;
// Initialize Partition
void initPartition(Partition *p) {
p->capacity = 10;
p->size = 0;
p->parts = malloc(sizeof(char*) * p->capacity);
}
// Add part to Partition
void addPart(Partition *p, char *part) {
if (p->size == p->capacity) {
p->capacity *= 2;
p->parts = realloc(p->parts, sizeof(char*) * p->capacity);
}
p->parts[p->size++] = strdup(part);
}
// Remove last part from Partition
void removeLastPart(Partition *p) {
if (p->size > 0) {
free(p->parts[p->size - 1]);
p->size--;
}
}
// Print one partition
void printPartition(Partition *p) {
for (int i = 0; i < p->size; i++) {
printf("%s", p->parts[i]);
if (i != p->size - 1) printf(", ");
}
printf("\n");
}
// Backtracking function to find palindrome partitions
void backtrack(char *s, int start, Partition *current) {
int n = strlen(s);
if (start == n) {
printPartition(current); // print one valid partition
return;
}
for (int end = start; end < n; end++) {
if (isPalindrome(s, start, end)) {
int len = end - start + 1;
char *substr = malloc(len + 1);
strncpy(substr, s + start, len);
substr[len] = '\0';
addPart(current, substr); // add palindrome part
free(substr);
backtrack(s, end + 1, current); // recurse for remaining string
removeLastPart(current); // backtrack
}
}
}
int main() {
char s[] = "aab";
Partition current;
initPartition(¤t);
backtrack(s, 0, ¤t);
// Free allocated memory
for (int i = 0; i < current.size; i++) {
free(current.parts[i]);
}
free(current.parts);
return 0;
}
if (isPalindrome(s, start, end)) {
Check if current substring is palindrome to decide if we can partition here
addPart(current, substr); // add palindrome part
Add the palindrome substring to current partition list
backtrack(s, end + 1, current); // recurse for remaining string
Recurse to partition the rest of the string after current palindrome
removeLastPart(current); // backtrack
Remove last added part to try other partitions (undo choice)