LeetCode 22. Generate Parentheses

来源:互联网 发布:福建干部网络培训平台 编辑:程序博客网 时间:2024/05/01 00:16

问题

https://leetcode.com/problems/generate-parentheses/

解法

dfs + 剪枝

class Solution {public:    void search(vector<string>& res, char * s, int lNum, int depth, int n)    {        if (depth ==n)        {            if (lNum == 0)                res.push_back(string(s));            return;        }        // '('        s[depth] = '(';        if (lNum+1 <= (n-1-depth))            search(res, s, lNum+1, depth+1, n);        s[depth] = ')';        if (lNum-1 >= 0)            search(res, s, lNum-1, depth+1, n);    }    vector<string> generateParenthesis(int n) {        vector<string> ret;        if (n==0)            return ret;        char s[2*n+1];        s[2*n] = 0;        search(ret, s, 0, 0, 2*n);        return ret;    }};
0 0
原创粉丝点击