• 131. Palindrome Partitioning (Back-Track, DP)


    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"]
      ]

    思路: 首先使用动态规划纪录从i到j是否是回文数;然后遍历字符串,对于dp[depth][i]有选择与不选择两种情况,所以使用带回溯的递归,回溯法注意在递归返回后要将递归前改动的内容复原。

    class Solution {
    public:
        void backTracking(string s, int depth, vector<vector<bool>>& dp, vector<string>& current){
             for(int i = depth; i <s.length(); i++){
                 if(dp[depth][i]){
                     current.push_back(s.substr(depth, i-depth+1));
                     if(i==s.length()-1) ret.push_back(current);
                     else backTracking(s,i+1, dp,current);
                     current.pop_back(); //back track
                 } 
             }
        }
        vector<vector<string>> partition(string s) {
            //dp[i][j]: s[i...j] is parlindrome
            //dp[i][j] = dp[i-1][j+1] && s[i]==s[j]
            //traverse order: shorter one should be checked first, like insert sort
            int len = s.length();
            vector<vector<bool>> dp(len, vector<bool>(len, false));
            vector<string> current;
            for(int i = 0; i < len; i++) dp[i][i]=true;
            for(int i = 1; i < len; i++){
                for(int j = 0; j < i; j++){ //traverse the length
                    if(s[i]==s[j]){
                        if(j==i-1) dp[j][i] = true;
                        else dp[j][i]=dp[j+1][i-1];
                    }
                }
            }
            backTracking(s, 0, dp, current);
            return ret;
        }
    private: 
        vector<vector<string>> ret;
    };
  • 相关阅读:
    【总结整理】javascript的函数在if中调用时是否加括号---与.net的不同之处
    【总结整理】javascript的函数调用时是否加括号
    【总结整理】JavaScript的DOM事件学习(慕课网)
    关于overflow:hidden (转)
    CSS
    HTML
    jQuery
    函数
    装饰器
    python的条件与循环1
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4855296.html
Copyright © 2020-2023  润新知