22. Generate Parentheses
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]Input: n = 1
Output: ["()"]public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<String>();
dfs(list,"(", 1, 0, n);
return list;
}
public void dfs(List<String> list, String temp, int open, int close, int n) {
if (temp.length() == n * 2) {
list.add(temp);
return;
}
if (open < n) dfs(list, temp + "(", open + 1, close, n);
if (open > close) dfs(list, temp + ")", open, close + 1, n);
}Last updated