zoukankan      html  css  js  c++  java
  • 131. 分割回文串-回溯-中等

    问题描述

    给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。

    返回 s 所有可能的分割方案。

    示例:

    输入: "aab"
    输出:
    [
    ["aa","b"],
    ["a","a","b"]
    ]

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/palindrome-partitioning

    解答

    //backtrack
    class Solution {
        List<List<String>> res;
        public boolean check(String str,int left,int right){
            while(left < right){
                if(str.charAt(left) != str.charAt(right)){
                    return false;
                }
                left++;
                right--;
            }
            return true;
        }
        public void backtrack(int start, String s, Stack<String> output){
            for(int i=start;i<s.length();i++){
                String temp = s.substring(start, i+1);
                if(check(temp, 0, temp.length()-1)){
                    output.push(temp);
                    if(i==s.length()-1)res.add(new ArrayList<String>(output));
                    backtrack(i+1, s, output);
                    output.pop();
                }
            }
        }
        public List<List<String>> partition(String s) {
            res = new ArrayList<List<String>>();
            backtrack(0, s, new Stack<String>());
            return res;
        }
    }
  • 相关阅读:
    2016.7.31整机升级计划
    UVa 1588
    UVa1587
    Jzoj4714 公约数
    Jzoj4714 公约数
    Jzoj4713 A
    Jzoj4713 A
    Jzoj4711 Binary
    Jzoj4711 Binary
    Jzoj4710 Value
  • 原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13760638.html
Copyright © 2011-2022 走看看