leetcode 022 —— Generate Parentheses

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:

"((()))", "(()())", "(())()", "()(())", "()()()"

思路:只要左括号数目大于右括号的数目,即是合法的。采用递归

class Solution {
public:
	vector<string> generateParenthesis(int n) {
		vector<string> res;
		scan(0, 0, "", n, res);
		return res;
	}
	void scan(int l, int r, string path, int &n, vector<string> &res){
		if (r == n){
			res.push_back(path);
			return;
		}
		if (l<n)
		scan(l + 1, r, path+'(', n, res);//这条分支执行完后就会进入下一个if,而且每个分支一定能有结果
		if (r<l)
		scan(l, r + 1, path+')' , n, res);
	}
};





阅读更多
上一篇leetcode 021 —— Merge Two Sorted Lists
下一篇阿里一面
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭