用1,2,3,...,9组成3个三位数abc,def和ghi,每个数字恰好使用一次,要求abc:def:ghi=1:2:3。输出所有解。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int a[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
char found = 0;
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void getNum(int begin, int n)
{
int i, first, second, third;
if (found)
{
return;
}
if (begin >= n)
{
first = a[0]*100+a[1]*10+a[2];
second = a[3]*100+a[4]*10+a[5];
third = a[6]*100+a[7]*10+a[8];
if ((2*first == second)
&& (3*first == third))
{
printf("first = %d\n", first);
printf("second = %d\n", second);
printf("third = %d\n", third);
found = 1;
return;
}
}
else
{
for (i = begin; i < n; i++)
{
swap(&a[begin], &a[i]);
getNum(begin+1, n);
swap(&a[begin], &a[i]);
}
}
}
int main()
{
getNum(0, 9);
return 0;
}