leetcode: Generate Parentheses

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:

"((()))", "(()())", "(())()", "()(())", "()()()"

思路

对于第k个元素,考虑以下两种情况:

  1. 前k - 1个元素中'('出现次数小于n,第k个元素可以是'('。
  2. 前k - 1个元素中')'出现的次数小于'(',第k个元素可以是')'。
class Solution {
public:
    void internalGenerateParenthesis(vector<string> & result,
            string &s,
            int n,
            int left_num,
            int right_num) {
        if ((n == left_num) && (n == right_num)) {
            result.push_back(s);
        }
        
        if (left_num < n) {
            s.push_back('(');
            internalGenerateParenthesis(result, s, n, left_num + 1, right_num);
            s.pop_back();
        }
        
        if (right_num < left_num) {
            s.push_back(')');
            internalGenerateParenthesis(result, s, n, left_num, right_num + 1);
            s.pop_back();
        }
    }
    
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        string s;
        
        internalGenerateParenthesis(result, s, n, 0, 0);
        
        return result;
    }
};

 

posted @ 2013-10-28 18:17  移山测试工作室黑灯老师  阅读(1045)  评论(0编辑  收藏  举报
count website visits
Buy Computers