题解 | #括号生成#

括号生成

https://www.nowcoder.com/practice/c9addb265cdf4cdd92c092c655d164ca?tpId=295&tqId=725&ru=%2Fpractice%2Fc76408782512486d91eea181107293b6&qru=%2Fta%2Fformat-top101%2Fquestion-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D295

递归的使用

class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param n int整型 
     * @return string字符串vector
     */
    vector<string> generateParenthesis(int n) {
      if (n == 0) {
        return std::vector<std::string>();
      }
      
      std::string tmp;
      std::vector<std::string> str;
      
      recursion(0, 0, n, str, tmp);
      
      return str;
    }
  private:
    void recursion(int left, int right, const int &n, std::vector<std::string> &str, std::string tmp) {
      if (left == n && right == n) {
        str.push_back(tmp);
        return ;
      }
      
      if (left < n) {
        recursion(left + 1, right, n, str, tmp + '(');
      }
      
      if (right < left && right < n) {
        recursion(left, right + 1, n, str, tmp + ')');
      }
    }
};
全部评论

相关推荐

北漂的牛马人:211佬,包进的,可能是系统问题
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务