问题描述
https://leetcode.com/problems/generate-parentheses/
解决思路(2019-12-22)
递归回溯
代码
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
helper("", res, n, 0, 0);
return res;
}
public void helper(String curr, List<String> res, int n, int left, int right){
//all left and right has been added into curr, then add curr into res
if(left == n && right == n){
res.add(curr);
return;
}
//deal with wrong cases
if(right > left){
return;
}
//add left parenthese
if(left < n){
helper(curr + '(', res, n, left + 1, right);
}
//add right parenthese
if(right < n){
helper(curr + ')', res, n, left, right + 1);
}
}
}
效率探究
时间复杂度:O(2^n)
空间复杂度:O(n)
解决思路(2019-07-15)
利用递归,回溯法进行迭代,注释方法写的挺清楚的。
代码
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new LinkedList<>();
helper("", res, n, 0, 0);
return res;
}
//left represents amounts of '(' has been added to curr. Right represents ')'
public void helper(String curr, List<String> res, int n, int left, int right){
//all '(' and ')' has been added to curr correctly, so add curr to res
if(right == n && left == n){
res.add(curr);
return;
}
//the amounts of ')' could not be more than the left, like '())'
if(right > left){
return;
}
//when the amount of left and right brackets are less than n, then add them to curr
if(left < n){
helper(curr + '(', res, n, left + 1, right);
}
if(right < n){
helper(curr + ')', res, n, left, right + 1);
}
}
}
效率探究
时间复杂度:O(n!) ~ O(2^n)
空间复杂度:O(n)