第13周作业2(LeetCode22)

来源:互联网 发布:淘宝客知名论坛 编辑:程序博客网 时间:2024/06/03 19:31

1. 题目描述

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:

[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

2. 解决思路

本题主要是利用递归回溯的思想来解决,而解决此题的关键在于一个条件判断(这个也是借鉴了网上的解法)。在参考代码的启发下,我也使用几个实例验证了一下,确实对这位博主总结规律,自己摸索条件的能力比较佩服,这种态度值得学习。下面列出了关键的算法代码:

3. 关键代码

class Solution {public:     vector<string> generateParenthesis(int n)       {          vector<string> rs;          string s;          genParenthesis(rs, s, n, n);          return rs;      }      void genParenthesis(vector<string> &rs, string &s, int left, int right)      {          if (left==0)          {              rs.push_back(s);              rs.back().append(right, ')');              return;          }          s.push_back('(');          genParenthesis(rs, s, left-1, right);          s.pop_back();          if (left < right)          {              s.push_back(')');              genParenthesis(rs, s, left, right-1);              s.pop_back();          }      }  };
原创粉丝点击