zoukankan      html  css  js  c++  java
  • [Leetcode] Palindrome Partitioning I

        最近要开始准备找工作了,开始做Leetcode 上面的面试题,暂定每天至少一道。下面是第一道题:

    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。附加要求是返回的所有子串必须是回文串,所以需要对每一个子串都判断是不是回文。通过分析和观察示例可以发现,不同的分割结果中有许多相同的子串。在DFS的递归过程中,可能会多次走过同一个子串。如果每次都要对子串进行回文判定,无疑会导致许多重复劳动。所以此处可以通过DP来对DFS进行加速。
    class Solution
    {
    public:
        vector<vector<string> > res_all; //用来存放所有可能的分割结果
        vector<string> res; //用来存放某一个分割结果
    	bool** flag;  //DP 用来记录子串是否是回文,若flag[i][j] == true, 则s_ij为回文串
    	bool isPali(string s){
    		int len = s.length();
    	for(int i = 0;i<=len/2;i++)
    		if(s[i] != s[len-i-1]) return 0;
    	return 1;	
    	}
    	vector<vector<string> > partition(string s){
    	 int len = s.length();
    	  res_all.clear();res.clear();
     flag = new bool*[len];
     for(int i =0;i<len;i++){
    	 flag[i] = new bool[len];
    	 memset(flag[i],0,len);
     }
     for(int i = 0;i<len;i++){
    	 flag[i][i] = true;
    	 if(i<len-1 && s[i] == s[i+1]) flag[i][i+1]=true;
     }
     for(int i = 1;i<=len-1;i++){ // i is the step size
    	 for(int j=0;j<=len-i-1;j++){  // j is the begin of each loop
    		int k = j+i;
    		if(s[j] == s[k])
    			if(flag[j+1][k-1]){
    				flag[j][k] = true;
    			}
    	 }
     }
    //前面是先用DP找出所有可能的回文子串,下面是使用DFS来构造所有可能的回文分割结果 DFS(s, len, -1); return res_all; } void DFS(string s, int len, int lf){ if(lf == (len-1)){ res_all.push_back(res); return; } int next = lf+1; for(int i =next;i<=len-1;i++){ if(flag[next][i] == true){ res.push_back(s.substr(next,i-next+1)); DFS(s,len,i); res.pop_back(); } } } };

      

  • 相关阅读:
    搭建非域AlwaysOn win2016+SQL2016
    从0开始搭建SQL Server AlwaysOn 第四篇(配置异地机房节点)
    从0开始搭建SQL Server AlwaysOn 第二篇(配置故障转移集群)
    从0开始搭建SQL Server AlwaysOn 第三篇(配置AlwaysOn)
    从0开始搭建SQL Server AlwaysOn 第一篇(配置域控)
    四、基于Windows 2012配置SQL Server 2014 AlwaysOn
    三、安装SQLserver 2014(For AlwaysOn)
    二、 Windows 2012配置故障转移(For SQLServer 2014 AlwaysOn)
    Mybatis-SQL语句构建器类及日志
    Mybatis-JavaAPI
  • 原文地址:https://www.cnblogs.com/CGwolke/p/3258380.html
Copyright © 2011-2022 走看看