1. 程式人生 > >LeetCode-22-Generate Parentheses

LeetCode-22-Generate Parentheses

ati 數字 str 描述 function nth oid 數量 med

算法描述:

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,同時右括號數量不能大於左括號。

    vector<string> generateParenthesis(int n) {
        vector<string> results;
        generate(results, "", 0,0,n);
        return results;
    }
    
    void generate(vector<string>& results, string curr, int left, int right, int n){
        if(curr.size() == 2*n){
            results.push_back(curr);
            
return; } string tmp = ""; if(left < n){ tmp = curr +"("; generate(results,tmp, left+1, right, n); } if(right < left){ tmp = curr + ")"; generate(results,tmp, left, right+1,n); } }

LeetCode-22-Generate Parentheses