http://oj.leetcode.com/problems/palindrome-partitioning/
bool is_hw(int i, int j, string s, vector<vector<int>>& table) {
if (table[i][j] != 0) {
return table[i][j] > 0;
}
if (s[i] != s[j]) {
table[i][j] = -1;
return false;
} else {
if (j - i <= 2) {
table[i][j] = 1;
return true;
} else {
table[i][j] = is_hw(i+1, j-1, s, table);
return table[i][j] > 0;
}
}
}
// we are processing s[i, j];
void partition(vector<vector<string>>& ret, vector<string>& a, vector<vector<int>>& table, string s, int i, int j) {
if (i >= s.size()) {
ret.push_back(a);
return;
}
for (int e = i; e <= j; e++) {
if (is_hw(i, e, s, table)) {
string slice = s.substr(i, e - i + 1);
a.push_back(slice);
partition(ret, a, table, s, e+1, j);
a.pop_back();
}
}
}
void get_all_hw(string s) {
int l = s.size();
vector<vector<int>> table(l, vector<int>(l, 0));
vector<vector<string>> ret;
vector<string> t;
partition(ret, t, table, s, 0, l-1);
for (int i = 0; i < ret.size(); i++) {
for (int j = 0; j < ret[i].size(); j++) {
printf("%s ", ret[i][j].c_str());
}
printf("\n");
}
system("pause");
}