2016-10-19 4 views
0

私はleetcodeアルゴリズムlinkをやっています。leetcode括弧のアルゴリズムを生成

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: 

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

私は完全にそれについては考えています。

私は、組み合わせの数は、カタラン数

に等しいが、私は

誰かが私にいくつかのヒントを与えることができるすべての組み合わせを一覧表示する方法がわからない知っているのですか?コードは私にとって良いものではありません

+0

:ここ

は、私の解決策でした!私はもう少し説明を追加しました。見てみましょう:) –

答えて

1

(と、それぞれ変数(と変数)を記録するための左右の変数から始めることを考えています。

助けるために喜ん
public class Solution { 
    private void helper(List<String> res, String present, int left, int right, int n) { 
     // When you've finished adding all parenthesis 
     if (left == n and right == n) { 
      res.push_back(str); 
      return; 
     } 
     // You have left parenthesis available to add 
     if (left < n) { 
      helper(res, present + "(", left + 1, right, n); 
     } 
     // You can add right parenthesis only when you have more left parenthesis already added otherwise it won't be balanced 
     if (left > right) { 
      helper(res, present + ")", left, right + 1, n); 
     } 
    } 

    public List<String> generateParenthesis(int n) { 
     List<String> res = new ArrayList<String>(); 
     if (n == 0) { 
      return res; 
     } 
     helper(res, "", 0, 0, n); 
     return res; 
    } 
} 
+0

ありがとう、私はこの再帰的な解決策を理解するために重要な左右の店舗についてのあなたの情報 – nickang