zoukankan      html  css  js  c++  java
  • 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;
    };
  • 相关阅读:
    15、TSA数据上传(https://www.ncbi.nlm.nih.gov/genbank/tsaguide/#SP)
    14、SRA数据上传
    14、批量处理文件
    .net mvc 利用分部视图局部刷新.
    观察者模式(Observer)
    内存和性能
    DOM中的事件对象(event)
    HTML事件处理程序
    惰性载入函数
    Comet之SSE(Server
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4855296.html
Copyright © 2011-2022 走看看