[leetcode] Palindrome Partitioning 解题报告

题目链接:  https://leetcode.com/problems/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"]
  ]

思路:DFS递归搜索每个可能的子串,即每个子串长度可能为[1, length], 取一个长度为k的子串,判断其是否为回文数,分两种情况讨论:

1. 如果当前子串是回文数,将当前子串保存到数组里,然后剩下的字符作为原始字符串继续递归重复此操作,直到字符串剩余长度为0,将当前的一个解决方案保存起来

2. 如果不是回文数,k长度加1继续进行判断

代码如下:

class Solution {
public:
    bool isPalindrome(const string& str)
    {
        int i =0, j = str.size() -1;
        while(i<= j && str[i] == str[j])
            i++, j--;
        return i>j?true:false;
    }
    
    void DFS(vector<vector<string>>& result, vector<string>& tem, string str)
    {
        if(str.size() == 0)
        {
            result.push_back(tem);
            return;
        }
        for(int i =1; i <= str.size(); i++)
        {
            string substr = str.substr(0, i);
            if(isPalindrome(substr))
            {
                tem.push_back(substr);
                string restStr = str.substr(i);
                DFS(result, tem, restStr);
                tem.pop_back();
            }
        }
    }

    vector<vector<string>> partition(string s) {
        vector<vector<string>> result;
        vector<string> tem;
        DFS(result, tem, s);
        return result;
    }
};

参考:http://blog.csdn.net/ljphhj/article/details/22573983

你可能感兴趣的:(DFS,深度搜索,回朔)