枚舉法

Generate Parentheses

這題和二叉樹其實挺像的,因爲在每一個位置都只有兩種可能 "(" 和 ")".

(1)首先left如果大於0,就一直append left,相當於獲得一個有不同長度left (的集合

(2)然後針對每個left,append上相應的right ),相當於獲得right)的集合

Palindrome Partitioning

本質上是character subset問題.

(1)這個subset的字母必須達到一定長度纔可以

(2)每次加進來的不是一個字母,而是一個substring

(3)必須是palindrome纔可以加進來

public class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> res = new LinkedList<>();
        helper(res, new LinkedList<String>(), s, 0);
        return res;
    } 
    
    private void helper(List<List<String>> res, List<String> tmp, String str, int pos){
        if(pos == str.length()){
            res.add(new LinkedList<String>(tmp));
            return;
        }
        
        for(int i = pos; i < str.length(); i++){
            String sub = str.substring(pos, i+1);
            if(isPalindrome(sub)){
                tmp.add(sub);
                helper(res, tmp, str, i+1);
                tmp.remove(tmp.size()-1);
            }
        }
    }


//本題目本質上和subset沒啥區別,只是如果是palindrome的情況下才加進去   


    private boolean isPalindrome(String s){
        int i = 0, j = s.length() - 1;
        while(i < j){
            if(s.charAt(i) == s.charAt(j)){
                i++;
                j--;
            } else {
                return false;
            }
        }
        return true;
    }
}

Letter Combinations of a Phone Number

兩個阿拉伯數字相減就是絕對值

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章