Generate Parentheses
Given a number n and generate all possible valid combinations of n pairs of parentheses.
e.g: n=2 -> ["()()", "(())"]
Solution:
1. write a recursive function to use backtracking method. the parameters: left stands for the number of remaining '(' and right stands for the number of remaining ')', and a temp StringBuilder to store the string we built so far and the result list used when the current String is ok.
2. if left is 0, which means that we now only have ')' remaining, put all of the remaining ')' to the StringBuilder and add that to the result list. Then delete all ')' we just put in and return out of this method.
3. Then if the left is not 0, we can put a '(' into the StringBuilder and proceed to the next step by calling this function itself. After that delete the '(' we just put in so that the StringBuilder can maintain its cleanness.
4. If left is less than right, which means that there are more '(' in current StringBuilder than ')', we can put a ')' into the StringBuilder and proceed to the next step. After that delete the ')' we just put in.
5. from the main method, call this recursive function with parameters left = n, right = n, a new list and a new StringBuilder.
6. return the result list.
Code:
public class Solution { public List<String> generateParenthesis(int n) { List<String> result = new ArrayList<>(); StringBuilder temp = new StringBuilder(); helper(result, temp, n, n); return result; } private static void helper(List<String> result, StringBuilder temp, int left, int right){ if(left==0){ for(int i = 0; i < right; i++){ temp.append(')'); } result.add(temp.toString()); temp.delete(temp.length()-right, temp.length()); return; } temp.append('('); helper(result, temp,left-1,right); temp.deleteCharAt(temp.length()-1); if(left<right){ temp.append(')'); helper(result,temp, left, right-1); temp.deleteCharAt(temp.length()-1); } } }

浙公网安备 33010602011771号