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

时间复杂度为O(2^n),空间复杂度为 O(n)
递归时间,枚举,回溯
参考

代码

class Solution {
    public List> partition(String s) {
        List> res = new ArrayList<>();
        if(s == null || s.length() == 0) return res;
        helper(res, new ArrayList(), s);
        return res;
    }
    public void helper(List> res, List list, String s) {
        if(s.length() == 0) {
            res.add(new ArrayList<>(list));
            return;
        }
        for(int i = 0; i < s.length(); i++) {
            if(isPalindrome(s.substring(0, i + 1))) {
                list.add(s.substring(0, i + 1));
                helper(res, list, s.substring(i+1));
                list.remove(list.size() - 1);
            }
        }
    }
    public boolean isPalindrome(String s) {
        for(int i = 0; i < s.length() / 2; i++) {
            if(s.charAt(i) != s.charAt(s.length() - 1 - i)) {
                return false;
            }
        }
        return true;
    }
}

你可能感兴趣的:(131. Palindrome Partitioning)