LeetCode 131. Palindrome Partitioning--回溯法

来源:互联网 发布:易语言钓鱼源码大全 编辑:程序博客网 时间:2024/05/19 00:41

题目链接

131. 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.

For example, given s = "aab",
Return

[  ["aa","b"],  ["a","a","b"]]

解:回溯法“套路”按部就班:

1.写一个判断函数 isPalindrome ,判断字符串是不是palindrome(回文(指顺读和倒读都一样的词语)

2.写一个递归函数 split ,参数 head 代表从 head 位置开始找所有能构成回文的字符串(第一个一定是head位置的字符本身),找到后将子串放入 vector 中,再次调用 split 在子串尾位置开始找,当找到所有情况后,即将子串从 vector 中 pop 出。终止递归函数的条件就是当位置 head 已经超过了字符串的长度,这时候我们得到了一个解,将得到的 vector 放进结果 vector<vector> 后直接返回。

3. partition 中调用递归函数 split ,参数 head = 0

代码:

class Solution {public:    bool isPalindrome(int head, int tail, string origin) {        while (head < tail) {            if (origin[head] != origin[tail]) return false;            head++;            tail--;        }        return true;    }    void split(string str, int head, vector<string>& temp, vector<vector<string> >& all) {        int len = str.length();        if (head >= len) {            vector<string> copy;            copy.assign(temp.begin(), temp.end());            all.push_back(copy);            return;        }        for (int i = head; i < len; i++) {            if (isPalindrome(head, i, str)) {                temp.push_back(str.substr(head, i-head+1));                split(str, i+1, temp, all);                temp.pop_back();            }        }        return;    }    vector<vector<string> > partition(string s) {        vector<vector<string> > answer;        vector<string> temp;        split(s, 0, temp, answer);        return answer;    }};

 

原创粉丝点击