您的位置:首页 > 其它

[Leetcode-22]Generate Parentheses 生成圆括号

2017-08-11 20:43 369 查看

0. 题目概要

题目概要

分析

AC代码

Java AC代码

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:

[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]


输入n, 输出所有n个左右括号的括号序列。

1. 分析



2. AC代码

DFS方法记录了:

左括号个数

当前的”部分解”



class Solution {
public:
void help(int n, int x, int y, string now, vector<string> &answer){
if(y == n){
answer.push_back(now);
return;
}

if(x < n){
help(n, x+1, y, now + "(", answer);
}

if(x > y){
help(n, x, y+1, now + ")", answer);
}
}
vector<string> generateParenthesis(int n) {
vector<string> answer;
help(n, 0, 0, "", answer);
return answer;
}
};


3. Java AC代码

Java回溯法:

public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<String>();
backtrack(list, "", 0, 0, n);
return list;
}

public void backtrack(List<String> list, String str, int open, int close, int max){

if(str.length() == max*2){
list.add(str);
return;
}

if(open < max)
backtrack(list, str+"(", open+1, close, max);
if(close < open)
backtrack(list, str+")", open, close+1, max);
}


The idea here is to only add ‘(’ and ‘)’ that we know will guarantee us a solution (instead of adding 1 too many close). Once we add a ‘(’ we will then discard it and try a ‘)’ which can only close a valid ‘(‘. Each of these steps are recursively called.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: