zoukankan      html  css  js  c++  java
  • Palindrome Partitioning 分类: Leetcode(动态规划) 2015-04-14 11:00 24人阅读 评论(0) 收藏

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

    深搜
    class Solution {
    public:
        vector<vector<string>> partition(string s) {
            vector<vector<string>> ret;
            if(s.empty()) return ret;
            
            vector<string> path;
            dfs(0, s, path, ret);
            
            return ret;
        }
        
        void dfs(int index, string &s, vector<string> &path, vector<vector<string>> & ret) {
            if (index == s.size()) {
                ret.push_back(path);
            }
            
            for(int i = index; i < s.size(); ++i) {
                if (isPalindrome(s, index, i)) {
                    path.push_back(s.substr(index, i-index+1));
                    dfs(i+1, s, path, ret);
                    path.pop_back();
                }
            }
        }
        
        bool isPalindrome(const string &s, int start, int end) {
            while(start <= end) {
                if(s[start++] != s[end--])
                    return false;
            }
            return true;
        }
        
    };

     

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    CODE[VS] 1018 单词接龙
    Linux提示BOOT空间不足问题
    CODE[VS] 1017 乘积最大
    关于printf输出结果的一些问题
    CODE[VS] 1220 数字三角形
    redux
    Promise面试题
    学习Promise笔记
    js 事件委托 事件代理
    前端通信、跨域
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656936.html
Copyright © 2011-2022 走看看