For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
Idea: Recursion. We keep appending the left parentheses recursively if we have any left, while append the right parentheses only if the right parentheses are less than the left parentheses. When the number of left parentheses are the same as the right parentheses, add a result.
Time: O(n^2) Space: O(n^2)
Code
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result=new ArrayList<String>();
StringBuilder path=new StringBuilder();
dfs(result,path,n,n);
return result;
}
public void dfs(List<String> result,StringBuilder path,int left, int right)
{
if(left==0&&right==0)
{
result.add(path.toString());
}
if(left<0||right<0||left>right)
{
return;
}
dfs(result,path.append('('),left-1,right);
path.deleteCharAt(path.length()-1);
dfs(result,path.append(')'),left,right-1);
path.deleteCharAt(path.length()-1);
}
}
No comments:
Post a Comment