LeetCode:Generate Parentheses

題目連接html

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.spa

For example, given n = 3, a solution set is:code

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


 

全部組合的個數實際上是一個卡特蘭數htm

 

咱們這樣來構造一個合法的字符串:首先第一個位置確定是「(」,對於後面位置:blog

一、若是前一個字符是「(」:那麼咱們能夠在當前位置上加入「)」(字符「)」必定有剩餘);若是「(」字符還有剩餘,也能夠在當前位置加入「(」                          本文地址ip

二、若是前一個字符是「)」:若是當前「(」和「)」剩餘的數目不一樣(即其那面的括號沒有徹底匹配),能夠在當前位置上加入「)」;若是「(」字符還有剩餘,也能夠在當前位置加入「(」leetcode

 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         string tmpres(n<<1, '(');
 5         vector<string> res;
 6         helper(1, tmpres, res, n-1, n);
 7         return res;
 8     }
 9 private:
10     void helper(int index, string &tmpres, vector<string>&res, int leftNum, int rightNum)
11     {
12         if(index >= tmpres.size()){res.push_back(tmpres); return;}
13         if(tmpres[index-1] == '(')
14         {
15             tmpres[index] = ')';
16             helper(index+1, tmpres, res, leftNum, rightNum-1);
17             if(leftNum > 0)
18             {
19                 tmpres[index] = '(';
20                 helper(index+1, tmpres, res, leftNum-1, rightNum);
21             }
22         }
23         else
24         {
25             if(leftNum != rightNum)
26             {
27                 tmpres[index] = ')';
28                 helper(index+1, tmpres, res, leftNum, rightNum-1);
29             }
30             if(leftNum > 0)
31             {
32                 tmpres[index] = '(';
33                 helper(index+1, tmpres, res, leftNum-1, rightNum);
34             }
35         }
36     }
37 };

 

其實對於某個合法的字符串,咱們能夠發現從合法字符串的任何一個位置看,「(」的數目 >= ")"的數目,即剩餘的「(」的數目 <= 剩餘的")"數目, 所以就有如下更加簡潔的代碼字符串

 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         string tmpres;
 5         vector<string> res;
 6         helper(tmpres, res, n, n);
 7         return res;
 8     }
 9 private:
10     void helper(string &tmpres, vector<string>&res, int leftNum, int rightNum)
11     {
12         if(leftNum > rightNum)return;
13         if(leftNum == 0 && rightNum == 0)
14         {
15             res.push_back(tmpres);
16             return;
17         }
18         if(leftNum > 0)
19         {
20             tmpres.push_back('(');
21             helper(tmpres, res, leftNum-1, rightNum);
22             tmpres.pop_back();
23         }
24         if(rightNum > 0)
25         {
26             tmpres.push_back(')');
27             helper(tmpres, res, leftNum, rightNum-1);
28             tmpres.pop_back();
29         }
30     }
31 };

 

 【版權聲明】轉載請註明出處:http://www.cnblogs.com/TenosDoIt/p/3776583.htmlget

相關文章
相關標籤/搜索