题目
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:[“((()))”,“(()())”,“(())()”,“()(())”,“()()()”]
解
class Solution {public List<String> generateParenthesis(int n) {List<String> result = new ArrayList<>();dfs(n, n, "", result);return result;}public void dfs(int left, int right, String path, List<String> result) {if (left == 0 && right == 0) {result.add(path);}if (left > right) {return;}if (left < 0) {return;}dfs(left - 1, right, path + "(", result);dfs(left, right - 1, path + ")", result);}
}