LeetCode 22 題解--深度優先遍歷 -- 括號匹配

LeetCode 22 題解
AC 通過

public class LeetCode22 {
    
//    2^2n    局部不合法,不再遞歸
    
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<String>();
        
        // 遞歸
        gen(0,0,n,"",result);
        
        for(int i = 0; i < result.size();i++){
            System.out.println(result.get(i));
        }
        return result;
    }

    /**
     * @param i
     * @param j
     * @param n
     * @param result
     */
    private void gen(int left, int right, int n, String str,List<String> result) {
        // 遞歸的邊界   left < right 左括號的個數 必須大於等於右括號個數
        if(left > n || right > n || left < right) return ;
       
        if(left == n && right == n){
                result.add(str);
            return ;
        }

        gen(left + 1, right, n, str + "(", result);
        gen(left, right + 1, n, str + ")", result);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        new LeetCode22().generateParenthesis(3);
    }

}

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