【Leetcode】【Medium】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:

"((()))", "(()())", "(())()", "()(())", "()()()"

 

解题思路:

典型的回溯法应用,需要写一个回溯的递归方程;

思想是,对于一个未填充完全的符号串,可以有两种插入方式,分别对应两种递归:

  1、如果左括号 '(' 数量少于n,则string末尾插入 '(';

  2、如果右括号数<左括号数,则string末尾插入 ')';

 

解题步骤:

1、主程序新建一个用于保存各种解的数组,并调用回溯函数;

2、回溯函数,输入为待填充的解空间lst、某一个解result、当前已填充的左括号数left,当前已填充的右括号数right,题目要求的括号数n

  (1)当result长度为n*2时,即已经完成n个括号的填充,则将result放入lst中,并结束递归;

  (2)否则,如果left<n,插入一个‘(’,继续下一层递归;

  (3)如果right<left,插入一个‘)’,继续下一层递归;

 

代码:

 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         vector<string> lst;
 5         Backtracking(lst, "", 0, 0, n);
 6         return lst;
 7     }
 8     
 9     void Backtracking(vector<string> &lst, string result, int left, int right, int n) {
10         if (result.size() == n * 2) {
11             lst.push_back(result);
12             return;
13         }
14         
15         if (left < n) 
16             Backtracking(lst, result + '(', left+1, right, n);
17         
18         if (right < left)
19             Backtracking(lst, result + ')', left, right+1, n);
20     }
21 };

 

另:

//如何使用决策树实现,使叶子成为各种分配方式的集合?

posted @ 2015-03-02 10:52  胡潇  阅读(127)  评论(0编辑  收藏  举报