131. Palindrome Partitioning

来源:互联网 发布:淘宝美宝莲旗舰店假货 编辑:程序博客网 时间:2024/06/03 22:42

回文分割。

DP+dfs。

先判断str中任意字串是否是回文,用动态规划方法:

//construct the pailndrome checking matrix
// 1) matrix[i][j] = true; if (i==j) -- only one char
// 2) matrix[i][j] = true; if (i==j+1) && s[i]==s[j] -- only two chars
// 3) matrix[i][j] = matrix[i+1][j-1]; if s[i]==s[j] -- more than two chars

然后再用dfs来不断的分割str。

有个问题:在dfs中,会出现重复判断某一子串是否是回文,以及计算该子串的所有回文分割的情况。这样应该浪费了很多时间。
可以保存之前出现子串的分割结果,后面遇到时直接访问下就可以了。

class Solution {public:    vector<vector<string>> partition(string s) {        bool** mark = isPalindrome(s);        vector<vector<string>> out;        vector<string> temp;        dfs(s, 0, s.size()-1, temp, out, mark);        for(int i = 0; i < s.size()-1; ++i)            delete [] mark[i];        delete mark;        return out;    }    bool** isPalindrome(string s){        int size = s.size();        bool** mark = new bool*[size];        for(int i = 0; i < size; ++i)            mark[i] = new bool[size];        for(int i = size-1; i >= 0; --i){            for(int j = i; j < size; ++j){                if(i==j) mark[i][j] = true;                if(j-i==1) mark[i][j] = (s[i]==s[j]);                if(j-i>1) mark[i][j]=(s[i]==s[j])&&mark[i+1][j-1];            }        }        return mark;    }    void dfs(string s, int i, int j, vector<string> temp, vector<vector<string>>& out, bool**& mark){        if(i>j) out.push_back(temp);        for(int k = i; k <= j; ++k){            if(mark[i][k]) temp.push_back(s.substr(i,k-i+1));            else continue;            dfs(s,k+1,j,temp,out,mark);            temp.pop_back();         }    }};

//没有动态规划,直接判断子串是否回文的方法:

class Solution { //没有动态规划,直接判断子串是否回文的方法public:    vector<vector<string>> partition(string s) {        vector<vector<string>> out;        vector<string> temp;        dfs(s, 0, s.size()-1, temp, out);        return out;    }    void dfs(string s, int i, int j, vector<string> temp, vector<vector<string>>& out){        if(i>j) out.push_back(temp);        for(int k = i; k <= j; ++k){            if(isPalindrome(s,i,k)) temp.push_back(s.substr(i,k-i+1));            else continue;            dfs(s,k+1,j,temp,out);            temp.pop_back();         }    }    bool isPalindrome(const string& s, int start, int end) {        while(start <= end) {            if(s[start++] != s[end--])                return false;        }        return true;    }};


上面两种法子(加了DP和没加DP)运行时间都在40ms左右,加了dp效率并没有增加。而discuss中没有dp的却能跑到12ms。

我调试后发现问题在于:dfs中的变量path不是按引用传的。修改后:

    void dfs(string s, int i, int j, vector<string>& temp, vector<vector<string>>& out){        if(i>j) out.push_back(temp);        for(int k = i; k <= j; ++k){            if(isPalindrome(s,i,k)) temp.push_back(s.substr(i,k-i+1));            else continue;            dfs(s,k+1,j,temp,out);            temp.pop_back();         }    }


不论有没有加dp,时间都变成12ms了。

1 0
原创粉丝点击