LeetCode(22)--Generate Parentheses

来源:互联网 发布:c语言经典小游戏编程 编辑:程序博客网 时间:2024/05/24 05:24

这道题考虑用递归算法。截至条件是剩余的左括号和右括号数都为0,在递归时注意剩余的左括号数要小于右括号数。实现代码如下:

class Solution {public:   vector<string> generateParenthesis(int n) {        vector<string> res;        if (n < 1)return res;        helper(res, "", n, n);        return res;    }    void helper(vector<string> &v, string str, int left, int right)    {        if (left == 0 && right == 0)        {            v.push_back(str);            return;        }        if (left > 0)        {            helper(v, str + "(", left - 1, right);        }         if (right > 0 && left < right)        {            helper(v, str + ")", left, right - 1);        }    }};
原创粉丝点击