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.

Example:

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

subtracking,差点就看透答案了呢,partition我想给你🐎头上来一刀
 class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> result = new ArrayList<>();
        List<String> path = new ArrayList<>();  // 一个partition方案
        dfs(s, path, result, 0);
        return result;
    }
    // 搜索必须以s[start]开头的partition方案
    private static void dfs(String s, List<String> path,
                            List<List<String>> result, int start) {
        if (start == s.length()) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = start; i < s.length(); i++) {
            if (isPalindrome(s, start, i)) { // 从i位置砍一刀
                path.add(s.substring(start, i+1));
                dfs(s, path, result, i + 1);  // 继续往下砍
                path.remove(path.size() - 1); // 撤销上上行
            }
        }
    }
    private static boolean isPalindrome(String s, int start, int end) {
        while (start < end && s.charAt(start) == s.charAt(end)) {
            ++start;
            --end;
        }
        return start >= end;
    }
}

 思路来自leetcode discussion https://leetcode.com/problems/palindrome-partitioning/discuss/41963/Java%3A-Backtracking-solution.

 二刷:判断条件,何时断点值得思考

class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList();
        List<String> path = new ArrayList();
        dfs(res, path, s, 0);
        return res;
    }
    public void dfs(List<List<String>> res, List<String> path, String s, int start){
        if(start == s.length()) res.add(new ArrayList(path));
        for(int i = start; i < s.length(); i++){
            String tmp = s.substring(start, i+1);
            if(!isPal(tmp)) continue;
            path.add(tmp);
            dfs(res, path, s, i + 1);
            path.remove(path.size() - 1);
        }
    }
    public boolean isPal(String s){
        int start = 0; 
        int end = s.length() - 1;
        while(start <= end && s.charAt(start) == s.charAt(end)){
            start ++;
            end --;
        }
        return start >= end;
    }
}

 

posted @ 2019-03-12 13:28  Schwifty  阅读(119)  评论(0编辑  收藏  举报