Generate Parentheses
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Personally, I think
time complexity
= O(n! ) (not including time copying tmpStr), n is the input,
= O(n * n!) ( including time copying tmpStr).
space complexity
= O(n) (stack space usage),
= O(n) (stack + recursion space usage).
Code: Java
import java.util.List;
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<String>();
// Input checking.
if (n <= 0) {
list.add("");
return list;
}
String tmpStr = "";
for (int i = 0; i < n; i ++) tmpStr += "(";
helper(n, tmpStr, 0, list);
return list;
}
private void helper(int n, String tmpStr, int start, List<String> list) {
// Base case.
if (tmpStr.length() == 2 * n) {
if (isValid(tmpStr)) list.add(tmpStr);
return;
}
for (int i = start; i < tmpStr.length(); i ++) {
// Have a try.
tmpStr = tmpStr.substring(0, i + 1) + ")" +
tmpStr.substring(i + 1, tmpStr.length());
// Do recursion.
helper(n, tmpStr, i + 1, list);
// Roll back.
tmpStr = tmpStr.substring(0, i + 1) +
tmpStr.substring(i + 2, tmpStr.length());
}
}
private boolean isValid(String str) {
// Input checking.
if (str == null || str.length() < 2) return false;
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < str.length(); i ++) {
char curr = str.charAt(i);
if (curr == '(') stack.push(curr);
else {
if (stack.isEmpty()) return false;
stack.pop();
}
}
if (stack.isEmpty()) return true;
else return false;
}
}