Cracking the Coding Interview 8.5

Implement an algorithm to print all valid combinations of n-pairs of parentheses

 

#include<stdio.h>

void f(int idx,int left,int right,char *buf)
{
    if(left == 0 && right == 0)
    {
        buf[idx] = '\0';
        printf("%s\n",buf);
    }
    if(left>0)
    {
        buf[idx]='(';
        f(idx+1,left-1,right,buf);
    }
    if(right>left)
    {
        buf[idx]=')';
        f(idx+1,left,right-1,buf);
    }
}

int main()
{
    int n=1;
    char *buf = new char[n+1];
    f(0,n,n,buf);
    return 0;
}

 

posted @ 2014-08-21 11:17  米其林轮船  阅读(157)  评论(0编辑  收藏  举报