问题:
左“{”,右”}"括号各N个,请打印出所有正确的组合,比如当N=3,{}{}{},{}{{}},等为正确的组合。如果写的代码是recursive,能否用iterative再写一个;反之亦然。
py实现:
def foo(output, open, close, pairs): if open == pairs and close == pairs: print output else: if open<pairs: foo(output+'(', open+1, close, pairs) if close<open: foo(output+')', open, close+1, pairs) foo('', 0, 0, 3)
Cats萌萌