LeetCode 22. Generate Parentheses (Backtracking回溯法模板) C++

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

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

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

C++(Backtracking 回溯法)

class Solution {
public:
    vector<string> generateParenthesis(int n) {
    	vector<string> res;
    	backtrack(res,"" ,n ,0 ,0 );
    	return res;
	}
	void backtrack(vector<string> &v, string current, int max, int open,int close){
		if(current.size()== max*2 ){//some base case,递归出口 
		    v.push_back(current);
			return;
		}
		//decisions
		if(open < max) backtrack(v, current + "(", max, open + 1, close);//添加左括号,只要比max小就能添加。
		if(close < open) backtrack(v, current + ")" , max, open, close + 1);//添加右括号,需要右括号的数量比左括号少才能添加
	}
};

附回溯法模板

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;//backtracking 通常涉及一个数组,最后返回一个数组
    	backtrack(res,...);
    	return res;
	}
	void backtrack(vector<data> v,data temp,...  ){
	     if(...){//some base case
	        v.push_back(temp);//add something kind of data into the vector
	        return;
	     }
	     //making some decisions
	     //make all possible decisions in these recursive
	}
};

你可能感兴趣的:(LeetCode 22. Generate Parentheses (Backtracking回溯法模板) C++)