每日算法——leetcode系列


问题 Generate Parentheses

Difficulty: Medium

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:
"((()))", "(()())", "(())()", "()(())", "()()()"

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        
    }
};

翻译

括符生成

难度系数:中等

思路

此题难在要想到递归。
假设:左括符个数用left表示,右括符个数用right表示
递归终止条件: left = right = n
先要生成左括符,可以生成左括符的条件:left < n
生成右括符条件: right < left

代码

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        if (n > 0) {
            generator(n, 0, 0, "", result);
        }
        return result;
    }
    
private:
    void generator(int n, int left, int right, string s, vector<string> &result) {
        if (left == n && right == n) {
            result.push_back(s);
            return;
        }
        if (left < n) {
            generator(n, left+1, right, s + '(', result);
        }
        if (right < left) {
            generator(n, left, right + 1, s + ')', result);
        }
    }
};

carlblack
4 声望16 粉丝