I am having trouble in calculating the time complexity of program shown below. It is a simple program to generate valid parentheses such as "((()))" "(()())" etc. However, I don't really know how to estimate time complexity for this kind of problems.
It will be appreciated if you can share some techniques you find useful here. It will be the best if you can analyze the program I linked as an example : )
My aim :
Estimate time complexity for nontrivial program. Typically a recursive program which has some pruning.
I am looking for a fast estimate solution, not a rigorous mathematical proving.
Thank you in advance.
The code in question:
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> res = new ArrayList<String>();
String oneSolu = "";
Generate(n, n, res, oneSolu);
return res;
}
private void Generate(int l, int r, ArrayList<String> res, String oneSolu) {
if (l==0 && r==0) {
res.add(oneSolu);
return ;
}
//add left
if (l > 0) {
String t = oneSolu;
t += "(";
Generate(l-1, r, res, t);
}
if (r>l) {
String t = oneSolu;
t += ")";
Generate(l, r-1, res, t);
}
}
The number of valid parenthesis generated with n-pairs is nth catalan number which is defined as
2nCn/(n+1)but if u need more simplified bound then it isO(4^N). More generally any recursive function is upper bounded by its max branching factor and depth asO(b^d)if work done at each level isO(1)so in this case depth = 2N and branching factor is approximately 2 henceT(n) = 2^(2N)=4^N.