leetcode-Generate Parentheses (2014.4.18)

Generate Parentheses Total Accepted: 10265 Total Submissions: 33530 My Submissions

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個括號對,確保左括號在右括號之前,需要進行去重。要考慮時間複雜度。遞歸是解決子問題的。
class Solution {
public:
    void parenthese(int p,int q,vector<string> &str,string item){
       if(p==0&&q==0) {
  str.push_back(item);
 }else{
  if(p>0){
   parenthese(p-1,q,str,item+'(');
  }
  if(q>0&&q>p){
   parenthese(p,q-1,str,item+')');遞歸帶入如此出的q-1,都不是賦值操作
  }
 }
        
    }
    vector<string> generateParenthesis(int n) {
        vector<string> vec;
     if(n<=0) return vec;
     string ans;
      parenthese(n,n,vec,ans);
     return vec;
    }
};
注意限定條件。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章