Problem:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Method:
How to understand DFS? Determine how many branches we have? For each branch, we call recursive helper method. So overall, we will find out all the solutions for one branch and then go to another branch and do the same thing.
Remember: in each level, we have to make sure the variables are not changed, since we still need to go to the next branch.
Code:
public class Solution { ArrayList<String> res = new ArrayList<String>(); public ArrayList<String> generateParenthesis(int n) { if (n == 0) return res; helper(n, n, ""); return res; } public void helper(int left, int right, String item){ if (left > right) return; if (left == 0 && right == 0){ res.add(item); } if (left > 0){ helper(left-1, right, item + "("); // remember that one each level, you can't change the variables. } if (right > 0){ helper(left, right-1, item + ")"); } } }