Generate Parentheses(22)

Generate Parentheses

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

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

"((()))", "(()())", "(())()", "()(())", "()()()"遞歸

思路:向string 中插入( 和 ),每插入一個就減1。 那麼如何保證這個combination 是正確的呢?string

  1. 插入數量不超過nit

  2. 能夠插入 ) 的前提是 ( 的數量大於 )io

因此就獲得了遞歸的兩個條件。function

public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<String>();
        String paren = "";
        helper(result,paren, n, n);
        return result;
    }
    
    private void helper(List<String> result, String paren,int left, int right) {
        if (left == 0 && right == 0) {
            result.add(paren);
            return;
        }
        if (left > 0) {
            helper(result, paren + "(", left - 1, right);
        }
        if (right > 0 && left < right) {
            helper(result, paren + ")", left, right - 1);
        }
    }
}
相關文章
相關標籤/搜索