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
void back_tracting(vector<string> &result, int left, int right,string &tmp_result){
if(left==0&right==0){
result.push_back(tmp_result);
return;
}
if(left>0){
tmp_result += '(';
back_tracting(result,left-1,right,tmp_result);
tmp_result.pop_back();
}
if(right>left){
tmp_result+=')';
back_tracting(result,left,right-1,tmp_result);
tmp_result.pop_back();
}
}
通过pop_back回到上一个回溯点
网友评论