【回溯】B059_LC_分割回文串(選就是了)

一、Problem

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Input: "aab"
Output:
[
  ["aa","b"],
  ["a","a","b"]
]

二、Solution

方法一:回溯

class Solution {
    List<String> it;
    List<List<String>> all;
    boolean is(String s, int l, int r) {
        while (l < r) {
            if (s.charAt(l) == s.charAt(r)) {
                l++; r--;
            } else
                return false;
        }
        return true;
    }
    void dfs(int idx, String s) {
        if (idx == s.length()) {
            all.add(new LinkedList<>(it));
            return;
        }
        for (int i = idx; i < s.length(); i++) {
            if (is(s, idx, i)) {
                it.add(s.substring(idx, i+1));
                dfs(i+1, s);
                it.remove(it.size()-1);
            }
        }
    }
    public List<List<String>> partition(String s) {
        it = new LinkedList<>();
        all = new LinkedList<>();
        dfs(0, s);
        return all;
    }
}

複雜度分析

  • 時間複雜度:O(2n)O(2^n)
  • 空間複雜度:O(...)O(...)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章