Skip to content

Instantly share code, notes, and snippets.

@qudongfang
Created November 18, 2012 01:58
Show Gist options
  • Save qudongfang/4102766 to your computer and use it in GitHub Desktop.
Save qudongfang/4102766 to your computer and use it in GitHub Desktop.
a bit of code
/*
左“{”,右”}"括号各N个,请打印出所有正确的组合,比如当N=3,{}{}{},{{{}}},等为正确的组合。如果写的代码是recursive,能否用iterative再写一个;反之亦然。
*/
// gcc -std=c99 test.c && ./a.out
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <assert.h>
void
recursive(char *str, int *left, int *right, int n)
{
assert(NULL != str && NULL != left && n >= 0);
if (*right == n)
{
*str = '\0';
printf("%s\n", str - 2 * n);
return;
}
if (0 == *left)
{
*str = '{';
*left = 1;
recursive(str + 1, left, right, n);
}
else
{
if (*left < n)
{
*str = '{';
*left += 1;
recursive(str + 1, left, right, n);
*left -= 1;
}
if (*left > *right)
{
*str = '}';
*right += 1;
recursive(str + 1, left, right, n);
*right -= 1;
}
}
}
int
main(void)
{
char str[10] = {0};
int left = 0;
int right = 0;
int n = 3;
recursive(str, &left, &right, n);
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment