题目描述

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

示例 1:
输入:n = 3
输出:[“((()))”,”(()())”,”(())()”,”()(())”,”()()()”]
示例 2:
输入:n = 1
输出:[“()”]

提示:

  • 1 <= n <= 8

解法

暴力解法

JavaScript

暴力解法链接

  1. var generateParenthesis = function (n) {
  2. let set = new Set(['()']);
  3. for (let c = 2; c <= n; c++) {
  4. let nextSet = new Set();
  5. for (const s of set) {
  6. for (let j = 0; j <= s.length; j++) {
  7. nextSet.add(s.slice(0, j) + '()' + s.slice(j));
  8. }
  9. }
  10. set = nextSet;
  11. }
  12. return [...set];
  13. };

Java

  1. class Solution {
  2. public List<String> generateParenthesis(int n) {
  3. if (n == 1) {
  4. return Arrays.asList("()");
  5. }
  6. Set<String> hs = new HashSet<>();
  7. for (String s : generateParenthesis(n-1)) {
  8. for (int i = 0; i < 2*n-2; i++) {
  9. hs.add(s.substring(0,i) + "()" + s.substring(i,s.length()));
  10. }
  11. }
  12. return new ArrayList(hs);
  13. }
  14. }

dfs

JavaScript

  1. /*
  2. * @lc app=leetcode.cn id=22 lang=javascript
  3. *
  4. * [22] 括号生成
  5. */
  6. // @lc code=start
  7. /**
  8. * @param {number} n
  9. * @return {string[]}
  10. */
  11. var generateParenthesis = function (n) {
  12. let result = [];
  13. dfs('', n, n, result);
  14. return result;
  15. };
  16. function dfs(str, left, right, result) {
  17. if (left === 0 && right === 0) {
  18. result.push(str);
  19. return;
  20. }
  21. if (right < left) {
  22. return;
  23. }
  24. if (left !== 0) {
  25. dfs(str + '(', left - 1, right, result);
  26. }
  27. if (right !== 0) {
  28. dfs(str + ')', left, right - 1, result)
  29. }
  30. }
  31. // @lc code=end

Java

  1. class Solution {
  2. List<String> list=new ArrayList<>();
  3. public List<String> generateParenthesis(int n) {
  4. if (n<1||n>8){
  5. return null;
  6. }
  7. def("",0,0,n);
  8. return list;
  9. }
  10. public void def(String paths,int left,int right,int n){
  11. if(left>n||right>n||right>left){
  12. return;
  13. }
  14. if(paths.length()==2*n){
  15. list.add(paths);
  16. return;
  17. }
  18. def(paths+"(", left+1, right, n);
  19. def(paths+")", left, right+1, n);
  20. }
  21. }