LeetCode 22 — Generate Parentheses(C++ Java Python)

题目:http://oj.leetcode.com/problems/generate-parentheses/

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 = 3,一组方案集是:
"((()))", "(()())", "(())()", "()(())", "()()()"

分析:
        递归实现,如果左括号还有剩余,则可以放置左括号,如果右括号的剩余数大于左括号,则可以放置右括号。
C++实现:
class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;
    	generate(n, n, "", res);
    	return res;
    }

    void generate(int left, int right, string str, vector<string>& res)
    {
    	if(left == 0 && right == 0)
    	{
    		res.push_back(str);
    		return;
    	}
    	if(left > 0)
    	{
    		generate(left - 1, right, str + '(', res);
    	}
    	if(right > left)
    	{
    		generate(left, right - 1, str + ')', res);
    	}
    }
};
Java实现:
public class Solution {
    public ArrayList<String> generateParenthesis(int n) {
        ArrayList<String> res = new ArrayList<String>();
		generate(n, n, "", res);
		return res;
	}

	public void generate(int left, int right, String str, ArrayList<String> res) {
		if (left == 0 && right == 0) {
			res.add(str);
			return;
		}
		if (left > 0) {
			generate(left - 1, right, str + '(', res);
		}
		if (right > left) {
			generate(left, right - 1, str + ')', res);
		}
    }
}
Python实现:
class Solution:
    # @param an integer
    # @return a list of string
    def generateParenthesis(self, n):
        res = []
        self.generate(n, n, "", res)
        return res
    
    def generate(self, left, right, str, res):
        if left == 0 and right == 0:
            res.append(str)
            return
        if left > 0:
            self.generate(left - 1, right, str + '(', res)
        if right > left:
            self.generate(left, right - 1, str + ')', res)
        感谢阅读,欢迎评论!
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页