LeetCode Top 100 Liked Questions 22. Generate Parentheses (Java版; Medium)

welcome to my blog

LeetCode Top 100 Liked Questions 22. Generate Parentheses (Java版; Medium)

题目描述

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

第一次做, 有点混乱, 想着采用改变现场恢复现场的常规手段做, 结果绕进去了; 混乱的原因在于要控制左括号和右括号的数量, 一般只控制一种字符的数量, 这次控制了俩, 所以乱了, 不过这两种字符的数量是有不等式约束的: 左括号的数量小于等于n, 右括号的熟练小于等于左括号, 做题的时候没有利用这一点; 创建两个变量分别记录左右括号的数量

  • 创建两个变量记录左右括号出现的次数
  • 使用不等式进行约束
/*
原则:
左括号数量小于等于n
右括号数量小于等于左括号数量
*/
import java.util.ArrayList;
import java.util.Stack;

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        if(n<1)
            return res;
        Stack<String> s = new Stack<>();
        //s.push("(");
        StringBuilder sb = new StringBuilder();
        Core(res, "", 0, 0, n);
        return res;
    }
    public void Core(List<String> res, String curr, int open, int close, int n){
        //base case
        if(open==n){
            //最后要保证左右括号数量相等
            while(close<open){
                curr += ")";
                close++;
            }
            res.add(curr);
            return;
        }
        /*
        另一种base case, 从curr的长度出发
        if(curr.length()==2*n)
            res.add(curr);
        */
        //只要open小于n, 就可以加(
        if(open<n){
            Core(res, curr+"(", open+1, close, n);
        }
        //只要close
        if(close<open){
            Core(res, curr+")", open, close+1, n);
        }
    }
}

题解

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList();
        backtrack(ans, "", 0, 0, n);
        return ans;
    }

    public void backtrack(List<String> ans, String cur, int open, int close, int max){
        if (cur.length() == max * 2) {
            ans.add(cur);
            return;
        }

        if (open < max)
            backtrack(ans, cur+"(", open+1, close, max);
        if (close < open)
            backtrack(ans, cur+")", open, close+1, max);
    }
}

你可能感兴趣的:(LeetCode,Hot100,LikedQuestions,LeetCode)