题目描述

image.png

解题思路

本题难得地方就是该放啥括号,因为要满足括号有效。所以本题简单得做法就是使用剩余的左右括号数量来判断。
如果剩余左括号等于右括号,那么此时只能放左括号,不能放右括号,放了右括号就不合法了。
如果剩余左括号小于右括号,那么此时可以放左括号也可以放右括号

  • 如果左括号不为0,那还可以放左括号
  • 如果左括号为0,那左右括号都能放

    1. class Solution {
    2. public List<String> generateParenthesis(int n) {
    3. getParenthesis("", n, n);
    4. return res;
    5. }
    6. List<String> res = new ArrayList<>();
    7. public void getParenthesis(String str, int left, int right) {
    8. if (left == 0 && right == 0) {
    9. res.add(str);
    10. return;
    11. }
    12. // 剩余的 ( 和 ) 相等,那么就只能放左括号
    13. if (left == right) {
    14. getParenthesis(str + "(", left - 1, right);
    15. }
    16. else if (left < right) {
    17. // 剩余的左括号小于右括号,那么即可以放左括号也可以放右括号
    18. if (left > 0) {
    19. getParenthesis(str + "(", left - 1, right);
    20. }
    21. getParenthesis(str + ")", left, right - 1);
    22. }
    23. }
    24. }