Question: given a number N, find the possible string that makes up n pairs of parentheses
Algorithm: matching parentheses using stacks
1. "(", directly press "(" into Stack, string 2. ")", if the top of the stack is "(", the top element of the stack is displayed and ")" is added to the string.
public class Solution { private List<String> parenthesesList = new ArrayList<String>(); public List<String> generateParenthesis(int n) { Stack<String> stack = new Stack<String>(); dfs(stack, "", n); return parenthesesList; } /** * Algorithm: * * 1. Add "(", stack push "(" directly * 2. Add ")", if the top of stack is "(", pop it * */ public void dfs(Stack<String> stack, String parentheses, int nParentheses) { if (parentheses.length() >= nParentheses*2) { if (parentheses.length()==nParentheses*2 && stack.empty()) { parenthesesList.add(parentheses); } return ; } // push "(" stack.push("("); dfs(stack, parentheses+"(", nParentheses); stack.pop(); // push ")" if (!stack.empty() && stack.peek()=="(") { stack.pop(); dfs(stack, parentheses+")", nParentheses); stack.push("("); } }}