A non-recursive solution in Python:
#! /usr/bin/python
def valid(state,N):
cnt=0
for i in xrange(N):
if cnt<0:
return False
if (state&(1<
This basically examines the binary representation of each number in [0,2^n), treating a '1' as a '{' and a '0' as a '}' and then filters out only those that are properly balanced.