您的位置:首页 > 其它

[leetcode] 22.Generate Parentheses

2015-08-18 18:12 288 查看
题目:

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是括号的对数,那么最终的字符串中有2*n个符号,其中n个是’(‘, n个是’)’。所以我们对这2*n个位置进行扫描,查看能存放的符号的所有组合。

1.当所有的’(‘都出现了后,那么接下来的可能就只有剩余的’)’都加到当前字符串的后面这种可能。

当前位置存放下’(‘,继续扫描下一个位置。

如果前面位置的’(‘数大于’)’数,那么这个位置是可以放入’)’。

所以我们在代码中不光要保存当前扫描到的字符串的符号组成,还要保存’(‘与’)’的数目。

以上。

代码如下:

class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
if(n == 0)return result;
string temp = "";
getAllParenthesis(result, temp, n, 0, 0);
return result;

}
void getAllParenthesis(vector<string>& result, string temp, int &n, int l, int r) {
if(l == n) {
string s(n - r, ')');
temp += s;
result.push_back(temp);
return;
}
temp.push_back('(');
getAllParenthesis(result, temp, n, l + 1, r);
temp.pop_back();
if( r < l) {
temp.push_back(')');
getAllParenthesis(result, temp, n, l, r + 1);
temp.pop_back();
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: