22.括号生成

110 阅读1分钟

题目描述

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

题解

采用回溯法,记左括号的数量为open,右括号的数量为close,只要open<n,就可以加入左括号,只要close<open就可以加入右括号。

代码

  • Java

Java中,除去最后一个字符的方法为s.substring(start,end),Java和C++都是只能“+”,但是不能“-”。

class Solution {
    List<String> res=new ArrayList<>();
    void backtrack(String path,int open,int close,int n){
        if(path.length()==2*n){
            res.add(path);
            return;
        }
        if(open<n){
            path+="(";
            backtrack(path,open+1,close,n);
            path=path.substring(0,path.length()-1);
        }
        if(close<open){
            path+=")";
            backtrack(path,open,close+1,n);
            path=path.substring(0,path.length()-1);
        }
    }
    public List<String> generateParenthesis(int n) {
        String path=new String();
        backtrack(path,0,0,n);
        return res;
    }
}
  • C++
class Solution {
public:
    void backtrack(string &path,vector<string>& res,int open,int close,int n){
        if(path.length()==2*n){
            res.push_back(path);
            return;
        }
        if(open<n){
            path=path+"(";
            backtrack(path,res,open+1,close,n);
            path.pop_back();
        }
        if(close<open){
            path=path+")";
            backtrack(path,res,open,close+1,n);
            path.pop_back();
        }
    }
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        string path;
        backtrack(path,res,0,0,n);
        return res;
    }
};

题目链接(leetcode-cn.com/problems/ge…