leetCode の「Generate Parentheses」を解いてみた。
https://leetcode.com/problems/generate-parentheses/
この問題は、与えられた数 n に対応する、"(" と ")" の妥当な組み合わせを全て作成するというもの。
例えば、n = 3 の時は以下になる。
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
提出したコードは以下。
public List<String> generateParenthesis(int n) { List<String> result = new ArrayList<>(); helper(result, "", 0, 0, n); return result; } private void helper(List<String> result, String current, int openCount, int closeCount, int max) { if ((openCount + closeCount) == max * 2) { // 脱出条件 result.add(current); return; } if (openCount < max) { // "(" は、使用数が上限に達していなければ使用可。 helper(result, current + "(", openCount + 1, closeCount, max); } if (closeCount < openCount) { // ")" は、"(" より使用数が少ない時のみ使用可。 helper(result, current + ")", openCount, closeCount + 1, max); } }
ポイントは、上記のコメントにも書いたが、"(" を使用可能な条件と ")" を使用可能な条件を整理して、コードに落とし込むところ。
上記を提出した結果は以下の通り。
8 / 8 test cases passed. Status: Accepted Runtime: 1 ms Memory Usage: 39.5 MB Your runtime beats 84.44 % of java submissions.