For such recursive problems check if f(n) can be built from f(n-1) , by inserting an instance of n = 1
This is a hint for general recursive problem
Example : n = 1 : ()
n = 2 : ()() , (())
n = 3 : ()()() , (())() , () (()) , (()()) , ((()))
f(3) can be found from f(3-1) , i,.e f(2) , by adding a single pair of parenthesis to f(3-1) inside every existing pair of parenthesis
Eg. - n = 2 : ()() -
(())() // inserted after first left parenthesis
() (()) // inserted after second left parenthesis
()()() // inserted at beginning
(()) -
(()()) // inserted after first left parenthesis
((())) // inserted after second left parenthesis
() (()) // inserted at beginning
Since () (()) occurs twice so use of set is required
Placing a pair at end would reduce to previous case as already did
eg - (())() inserted at end of (()) is same as inserted after first left parenthesis in ()()
public Set<String> generateParen(int remainder)
{
//HashSet will automatically check that no same values are inserted in set
Set<String> set = new HashSet<>();
//base case
if( remainder == 0 )
{
set.add("");
}
else
{
//recurse to f(n-1)
Set<String> prev = generateParen(remainder-1);
for(Strring str : prev)
{
for( int i = 0 ; i < str.length() ; ++i)
{
//if a left parenthesis is found
if(str.charAt(i) == '(')
{
String s = insertParenAt(str, i );
set.add(s);
}
}
//insert at beginning
set.add("()" + str);
}
}
}
public String insertParenAt (String parent , int index)
{
String left = parent.substring(0,index+1);
String right = parent.substring(index+1 , parent.length());
return left+ "()" + right ;
}
No comments:
Post a Comment