排列、组合算法 C语言

组合
#include <stdio.h>
#define N 12
#define M 5


int a[M];


void print(){
    int i;
    for(i = 0; i < M; ++i) 
        printf(" %d ",a[i]);
    printf("\n");
}

void comb(int n, int m)
{
    if (m == 0) {
        print();
        return;
    } else {
        for (int i = n-1; i >= 0; --i)
        {
            a[m-1] = i+1;
            comb(i, m-1);
        }
    }
}

int main()
{
    comb(N,M);
    return 0;
}

排列

#include <stdio.h>
#include <stdlib.h>

int sum = 0;
int visited[14];
int a[13];
int A, b, c, d;


void dfs(int step)
{
	if (step == 13) {
		//必须整除,变成乘法判断
		if (a[10] == a[11] * a[12]) sum++;
		return;
	}
	if (step == 10) {
		if (a[7] * a[8] != a[9]) return;
	}
	if (step == 7) {
		if (a[4] - a[5] != a[6]) return;
	}
	if (step == 4) {
		if (a[1] + a[2] != a[3]) return;
	}
	for (int i = 1; i <= 13; i++)
	{
		if (visited[i] == 0)
		{
			visited[i] = 1;
			a[step] = i;
			dfs(step + 1);
			visited[i] = 0;
		}
	}

}

int main()
{

	for (int i = 0; i<13; i++)
	{
		visited[i] = 0;
	}
	dfs(1);

	printf("%d\n", sum);
	printf("%d\t%d\t%d\t%d", A, b, c, d);
	getchar();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wcy708708/article/details/79744743