JunyiCode
3/28/2020 - 3:14 AM

131. Palindrome Partitioning

backtrack,多想多巩固

/*
不能加
else {
    break;
}
比如"efe", "ef"不是then break,但后面"efe"是

Note:
1. if(start == s.length())
2. cur.add(s.subtring(start, i + 1));
3. if(isPalindrome(s, start, i))
4. String: s.length()
*/


class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        backtrack(s, res, new ArrayList<>(), 0);
        return res;
    }
    
    public void backtrack(String s, List<List<String>> res, List<String> cur, int start) {
        if(start == s.length())
            res.add(new ArrayList<>(cur));        
        else {
            for(int i = start; i < s.length(); i++) {
                if(isPalindrome(s, start, i)) {
                    cur.add(s.substring(start, i + 1));
                    backtrack(s, res, cur, i + 1);
                    cur.remove(cur.size() - 1);
                } 
                // else {
                //     break;
                // }
            }
        }
    }
    
    //one character will return true!
    private boolean isPalindrome(String s, int low, int high) {
        while(low < high) {
            if(s.charAt(low++) != s.charAt(high--))
                return false;
        }
        return true;
    }
    
}