For example, with elements a,b,c,d
, there are 5 possible ways to take neighboring elements and reduce them into a single element, where exactly two elements mus
import java.util.ArrayList;
public class Parantheses {
private ArrayList<String> parStringList;
private int total;
public void exploreParantheses(String parString,int leftCnt,int rightCnt)
{
if (leftCnt < total)
{
exploreParantheses(parString + "(", leftCnt+1, rightCnt);
}
if ((rightCnt < total) &&(rightCnt < leftCnt))
{
exploreParantheses(parString + ")", leftCnt, rightCnt+1);
}
else if (rightCnt == total)
{
parStringList.add(parString);
}
}
public ArrayList<String> generateParanthesis(int numPars)
{
this.total = numPars;
this.parStringList = new ArrayList<String>();
exploreParantheses("", 0, 0);
return this.parStringList;
}
public static void main(String args[])
{
ArrayList<String> par;
par = (new Parantheses()).generateParanthesis(6);
for (String str: par)
System.out.println(str);
}
}
Here is actual code in Python, using generators to avoid using too much memory.
#! /usr/bin/python
def parenthesized (exprs):
if len(exprs) == 1:
yield exprs[0]
else:
first_exprs = []
last_exprs = list(exprs)
while 1 < len(last_exprs):
first_exprs.append(last_exprs.pop(0))
for x in parenthesized(first_exprs):
if 1 < len(first_exprs):
x = '(%s)' % x
for y in parenthesized(last_exprs):
if 1 < len(last_exprs):
y = '(%s)' % y
yield '%s%s' % (x, y)
for x in parenthesized(['a', 'b', 'c', 'd']):
print x
Recursion would be the way to go
split abcd into
(a) (bcd)
(ab) (cd)
(abc) (d)
These are some of the possibilities
Now recursively you can split each string(ignore the parenthesis while splitting) say for (bcd) one possibility
(b) (cd)
so now another combination is
((a)(b)(cd))
You can stop the recursion tree once you get a string with only one alphabet