云南專業(yè)做網(wǎng)站多少錢北京網(wǎng)站優(yōu)化常識
題目
數(shù)字 n 代表生成括號的對數(shù),請你設(shè)計一個函數(shù),用于能夠生成所有可能的并且 有效的 括號組合。
示例 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);}
}