//r-排列生成算法
//回溯法生成从n个元素中取出r个元素的所有排列情况
#include<stdio.h>
#include<string.h>
const int N = 10000;
int n, r;
int res[N];
bool used[N];
int counter;
void output()
{
counter++;
printf("Case %4d:", counter);
for(int i = 1; i <= r; i++)
printf(" %d", res[i]);
putchar('/n');
}
void p(int i)
{
int j;
for(j = 1; j <= n; j++)
{
if(!used[j])
{
used[j] = true;
res[i] = j;
if(i == r)
output();
else
p(i+1);
used[j] = false;
}
}
}
int main()
{
memset(used, false, sizeof(used));
while(scanf("%d%d", &n, &r)!=EOF)
{
counter = 0;
p(1);
}
return 0;
}
//
//r-错位排列生成算法
//回溯法生成从n个元素中取出r个元素的所有错位排列情况(第i个位置上的元素不为i)
#include<stdio.h>
#include<string.h>
const int N = 10000;
int n, r;
int res[N];
bool used[N];
int counter;
void output()
{
counter++;
printf("Case %4d:", counter);
for(int i = 1; i <= r; i++)
printf(" %d", res[i]);
putchar('/n');
}
void p(int i)
{
int j;
for(j = 1; j <= n; j++)
{
if(!used[j] && i!=j)
{
used[j] = true;
res[i] = j;
if(i == r)
output();
else
p(i+1);
used[j] = false;
}
}
}
int main()
{
memset(used, false, sizeof(used));
while(scanf("%d%d", &n, &r)!=EOF)
{
counter = 0;
p(1);
}
return 0;
}
//
//r-组合生成算法
//回溯法生成从n个元素中取出r个元素的所有组合情况
#include<stdio.h>
#include<string.h>
const int N = 10000;
int n, r;
int res[N];
bool used[N];
int counter;
void output()
{
counter++;
printf("Case %4d:", counter);
for(int i = 1; i <= r; i++)
printf(" %d", res[i]);
putchar('/n');
}
void c(int i)
{
int j;
for(j = res[i-1]+1; j <= n; j++)
{
if(!used[j])
{
used[j] = true;
res[i] = j;
if(i == r)
output();
else
c(i+1);
used[j] = false;
}
}
}
int main()
{
res[0] = 0;
memset(used, false, sizeof(used));
while(scanf("%d%d", &n, &r)!=EOF)
{
counter = 0;
c(1);
}
return 0;
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/Deutschester/archive/2009/06/24/4295650.aspx