LeetCode[22]:Generate Parentheses

Description

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

這道題的意思是給定一個數字n,讓生成共有n個括號的所有正確的形式。

解法1:遞歸

首先我們想到遞歸Recursion的方法。我們定義兩個變量left和right分別表示剩餘左右括號的個數,如果在某次遞歸時,左括號的個數大於右括號的個數,說明此時生成的字符串中右括號的個數大於左括號的個數,即會出現’)(‘這樣的非法串,所以這種情況直接返回,不繼續處理。如果left和right都爲0,則說明此時生成的字符串已有3個左括號和3個右括號,且字符串合法,則存入結果中後返回。如果以上兩種情況都不滿足,若此時left大於0,則調用遞歸函數,注意參數的更新,若right大於0,則調用遞歸函數,同樣要更新參數。代碼如

public class Solution {
    public List<String> generateParenthesis(int n) {
        ArrayList<String> res = new ArrayList<String>();
        dfs(res, n, n, "");
        return res;
    }
    public void dfs(ArrayList<String> res,int left,int right, String str){
        if(left < 0 || right < 0 || left > right){
            return;
        }
        if(left == 0 && right == 0){
            res.add(str);
            return ;
        }
        if(left > 0){
            dfs(res, left - 1, right, str + '(');
        }
        if(right > 0){
            dfs(res, left, right - 1, str + ')');
        }
    }
}

解法2:

第二種結果通過觀察規律
n=1: ()

n=2: (()) ()()

n=3: (()()) ((())) ()(()) (())() ()()()
找左括號,每找到一個左括號,就在其後面加一個完整的括號,最後再在開頭加一個(),就形成了所有的情況,需要注意的是,有時候會出現重複的情況,所以我們用set數據結構,好處是如果遇到重複項,不會加入到結果中,最後我們再把set轉爲ArrayList即可,參見代碼如下:

public class Solution{
    public List<String> generateParenthesis(int n){
        Set<String> set = new HashSet<String>();
        if(n == 0){
            set.add("");
        }else{
            List<String> prev = generateParenthesis(n - 1);
            for(String str : prev){
                for(int i = 0; i < str.length(); i++){
                    if(str.charAt(i) == '('){
                        String s = insertInside(str, i);
                        set.add(s);
                    }
                }
                if(!set.contains("()" + str)){
                    set.add("()" + str);
                }
            }
        }
        return new ArrayList(set);
    }
    public String insertInside(String str, int leftindex){
        String left = str.substring(0, leftindex + 1);
        String right = str.substring(leftindex + 1, str.length());
        return left + "()" + right;
    }
}

類似題目

  • 類似題目:
  • Remove Invalid Parentheses
  • Different Ways to Add Parentheses
  • Longest Valid Parentheses
  • Valid Parentheses
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章