代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { public: vector<string> generateParenthesis(int n) { vector<string> res; dfs(res, "", n, n); return res; }
void dfs(vector<string> & res, string str,int left,int right) { if(left == 0 && right == 0) res.push_back(str); if(left > 0) dfs(res, str + "(", left - 1, right); if(right > left) dfs(res, str + ")", left, right - 1); } };
|
看见一个图片很直观,这里直接放出来了 图片来源:ChineseKawhi