括号生成

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

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:穷举法

通过递归的方式获取所有可能的组合,然后判断每一种组合是否是有效的括号组合,如果是,添加到结果集中,最后返回符合的结果集合。

解法二:回溯法

也是通过递归的方式,但是可以根据已经出现过的左右括号的个数来判断下一个字符可以是左括号还是右括号,这样最后递归得到的都是有效的括号组合,效率较高。

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. public class LeetCode_022 {
  4. /**
  5. * 暴力破解法
  6. *
  7. * @param n
  8. * @return
  9. */
  10. public static List<String> generateParenthesis(int n) {
  11. List<String> result = new ArrayList<>();
  12. generateAllPossibleResults(new char[2 * n], 0, result);
  13. return result;
  14. }
  15. /**
  16. * 递归方法:2*n 的字符数组,每一个字符都有2种可能,直到字符数组被填满,校验是否符合
  17. *
  18. * @param current
  19. * @param pos
  20. * @param result
  21. */
  22. public static void generateAllPossibleResults(char[] current, int pos, List<String> result) {
  23. if (pos == current.length) {
  24. // 当字符数组被填充满时,校验是否符合
  25. if (valid(current)) {
  26. result.add(new String(current));
  27. }
  28. } else {
  29. // 递归
  30. current[pos] = '(';
  31. generateAllPossibleResults(current, pos + 1, result);
  32. current[pos] = ')';
  33. generateAllPossibleResults(current, pos + 1, result);
  34. }
  35. }
  36. /**
  37. * 判断是否符合条件
  38. *
  39. * @param current
  40. * @return
  41. */
  42. public static boolean valid(char[] current) {
  43. int balance = 0;
  44. for (char c : current) {
  45. if (c == '(') {
  46. ++balance;
  47. } else {
  48. --balance;
  49. }
  50. if (balance < 0) {
  51. return false;
  52. }
  53. }
  54. return balance == 0;
  55. }
  56. static List<String> res = new ArrayList<>();
  57. /**
  58. * 方法二:回溯法
  59. *
  60. * @param n
  61. * @return
  62. */
  63. public static List<String> generateParenthesis2(int n) {
  64. if (n <= 0) {
  65. return res;
  66. }
  67. getParenthesis("", n, n);
  68. return res;
  69. }
  70. private static void getParenthesis(String str, int left, int right) {
  71. if (left == 0 && right == 0) {
  72. res.add(str);
  73. return;
  74. }
  75. if (left == right) {
  76. //剩余左右括号数相等,下一个只能用左括号
  77. getParenthesis(str + "(", left - 1, right);
  78. } else if (left < right) {
  79. //剩余左括号小于右括号,下一个可以用左括号也可以用右括号
  80. if (left > 0) {
  81. getParenthesis(str + "(", left - 1, right);
  82. }
  83. getParenthesis(str + ")", left, right - 1);
  84. }
  85. }
  86. public static void main(String[] args) {
  87. System.out.println("=====暴力破解法=====");
  88. List<String> strings = generateParenthesis(4);
  89. for (String string : strings) {
  90. System.out.println(string);
  91. }
  92. System.out.println("=====回溯法=====");
  93. List<String> strings1 = generateParenthesis2(4);
  94. for (String s : strings1) {
  95. System.out.println(s);
  96. }
  97. }
  98. }

【每日寄语】 一万个美丽的未来,抵不上一个温暖的现在。