LeetCode 131. Palindrome Partitioning--回溯法

題目鏈接

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;
    }
};

 

發佈了55 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章