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

一刷
题解:
用backtracking + dfs求解
dfs中需要起始位置,设置为left, 然后从left到末尾为right的位置,传入子函数判断是否为palindrome。然后以right的下一个作为dfs的子问题的起始位置。

public class Solution {
    private List<String> curList;
    private List<List<String>> res;
    
    public List<List<String>> partition(String str) {
        res = new ArrayList<>();
        curList = new ArrayList<>();
        bt(str, 0);
        return res;
    }
    
    private void bt(String str, int left){
        if(curList.size()>0 && left>=str.length()) res.add(new ArrayList<>(curList));
        
        for(int i=left; i<str.length(); i++){
            if(isPalindrome(str, left, i)){
                if(i == left) curList.add(Character.toString(str.charAt(i)));
                else curList.add(str.substring(left, i+1));//include the i
                bt(str, i+1);
                curList.remove(curList.size()-1);
            }
        }
    }
    
    private boolean isPalindrome(String str, int l, int r){
        if(l == r) return true;
        while(l<r){
            if(str.charAt(l) != str.charAt(r)) return false;
            l++;
            r--;
        }
        return true;
    }
}

二刷
DFS+backtracking

public class Solution {
    
    private List<String> curList;
    private List<List<String>> res;
    
    public List<List<String>> partition(String s) {
        res = new ArrayList<>();
        curList = new ArrayList<>();
        bt(s, 0);
        return res;
    }
    
    private void bt(String str, int left){
        if(curList.size()>0 && left>=str.length()) res.add(new ArrayList<>(curList));
        for(int i=left; i<str.length(); i++){
            if(isPalin(str, left, i)){//include i and left
                if(left == i) curList.add(Character.toString(str.charAt(left)));
                else curList.add(str.substring(left, i+1));
                bt(str, i+1);
                curList.remove(curList.size()-1);
            }
        }
    }
    
    private boolean isPalin(String str, int left, int right){
        if(left == right) return true;//one character
        while(left<right){
            if(str.charAt(left)!=str.charAt(right)) return false;
            left++;
            right--;
        }
        return true;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容