Palindrome Partitioning
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Personally I think, the time complexity is O(n^n), n is the length of the given string.
Thank you Dan Roche, the tight time complexity = O(n* (2^n)), check details below.
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> list;
vector<string> subList;
// Input validation.
if (s.length() <= 1) {
subList.push_back(s);
list.push_back(subList);
return list;
}
int len = s.length();
vector<vector<bool>> memo(len, vector<bool>(len));
for (int i = 0; i < len; i ++) {
for (int j = 0; j < len; j ++) {
if (i >= j) memo[i][j] = true;
else memo[i][j] = false;
}
}
int start = 0;
helper(s, start, list, subList, memo);
return list;
}
void helper(string s, int start,
vector<vector<string>> &list, vector<string> &subList,
vector<vector<bool>> &memo) {
// Base case.
if (start > s.length() - 1) {
vector<string> one_rest(subList);
list.push_back(one_rest);
return;
}
for (int len = 1; start + len <= s.length(); len ++) {
int end = start + len - 1;
memo[start][end] = (len == 1) ||
(memo[start + 1][end - 1] && s[start] == s[end]);
if (memo[start][end] == true) {
// Have a try.
subList.push_back(s.substr(start, len));
// Do recursion.
helper(s, end + 1, list, subList, memo);
// Roll back.
subList.pop_back();
}
}
}
};