题目描述

分析

考虑使用递归的方法。对于任意一段字符串,都会有它的长度(currLen)、未匹配的前括号数(unmatch)等信息。构造vector strVec存储符合题目要求的字符串。

  • 递归的终止条件:
    1. currLen == n,返回并将这个字符串加到strVec中
    2. unmatch + currLen == n,这时候未匹配前括号数与在题目要求下剩余的位置的数量相等,剩余的位置需要全放后括号,然后把操作后的字符串加入到strVec中,返回
  • 如果unmatch > 0那么可以给字符串末尾加上后括号")",再对其进行递归
  • 给字符串末尾加上前括号"(",再对其进行递归

代码

class Solution {
public:
    void creatParen(vector<string>& strVec, string str, int unmatch, int n) {//递归函数,这里的n是指预期的所有括号的总数,实际上为题目所给n的2倍
        int currLen = str.length();
        if(currLen == n){//终止条件1
            strVec.push_back(str);
            return;
        }
        if(currLen + unmatch == n){//终止条件2
            str.append(unmatch, ')');//向str添加unmatch个后括号")"
            strVec.push_back(str);
            return;
        }
        if(unmatch > 0){
            str.append(")");
            creatParen(strVec, str, unmatch - 1, n);
            str = str.substr(0, currLen);//复原str共下面的调用正常使用
        }
        str.append("(");
        creatParen(strVec, str, unmatch + 1, n);
    }
    vector<string> generateParenthesis(int n) {
        vector<string> strVec;
        creatParen(strVec, "", 0, 2*n);
        return strVec;
    }
};

运行结果

 posted on 2020-04-10 11:18  Nreyab  阅读(115)  评论(0)    收藏  举报