专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > C语言

C语言全排列,该如何解决

发布时间:2011-06-28 16:18:00 文章来源:www.iduyao.cn 采编人员:星星草
C语言全排列
求教 c语言:输入一个数,输出全排列。
如:
输入3:
输出: 123
  132
  231
  213
  312
  321
顺序无所谓。

------解决方案--------------------
C/C++ code
#include <stdio.h>
void perm(int* data, int n, int curr)
{
    if (curr==n-1)
    {
        for (int i = 0; i < n; ++i)
            printf("%d", data[i]);
        printf("\n");
    }
    else
    {
        for (int i = curr; i < n; ++i)
        {
            int t;
            t = data[curr], data[curr] = data[i], data[i] = t;
            perm(data, n, curr+1);
            t = data[curr], data[curr] = data[i], data[i] = t;
        }
    }
}

int main()
{
    int array[] = {1,2,3};
    perm(array, sizeof(array)/sizeof(array[0]), 0);
    return 0;
}
123
132
213
231
321
312
Press any key to continue

------解决方案--------------------
[code=C/C++][/code]
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
int n;
cin>>n;
vector<int> vect;
for(int i = 0; i != n; ++i ){
vect.push_back(i + 1);
cout<<i + 1;
}
cout<<'\n';
ostream_iterator<int> os(cout);
while(next_permutation(vect.begin(), vect.end() ) )
{
copy(vect.begin(), vect.end(), os);
cout<<'\n';

}
return 0;
}

/*
4
1234
1243
1324
1342
1423
1432
2134
2143
2314
2341
2413
2431
3124
3142
3214
3241
3412
3421
4123
4132
4213
4231
4312
4321
*/

------解决方案--------------------
/*
a b c d 全排列算法
*/

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

Permutation(char a[], int start, int end)
{
int i;
char temp;
if(start == end)
{
for(i = 0; i <= end; i++)
printf(" %c ",a[i]);
printf("\n");
}
else
{
for(i = start; i <= end; i++)
{
temp=a[start]; a[start]=a[i]; a[i]=temp;
Permutation(a, start+1, end);
temp=a[start]; a[start]=a[i]; a[i]=temp;
}
}
}

int main()
{
char A[] = "abcd";
Permutation(A,0,3);

// getch();
return 0;
}

------解决方案--------------------
输入一个字符串输入,输出每个字符的全排列除了'\0'
C/C++ code
#include <stdio.h> 
#include <string.h> 
#include <memory.h> 
int m;//记录字符串长度 
int n;//记录字符串中的字符种类数 
char map[256];//记录是哪几种字符 
int count[256];//记录每种字符有多少个 

void Make_Map(char *str)//统计字符串的相关信息 
{ 
int s[256]; 
int i; 
memset(s,0,sizeof(s)); 
memset(count,0,sizeof(count)); 
m=strlen(str); 
while(*str) 
{ 
s[*str]++; 
str++; 
} 
n=0; 
for (i=0;i<256;i++) 
if (s[i]) 
{ 
map[n]=i; 
count[n]=s[i]; 
n++; 
} 
} 

int stack[1000];//递归用的栈,并记录当前生成的排列 

void Find(int depth)//递归式回溯法生成全排列 
{ 
    int k=0;
if (depth==m) 
{ 
int i; 
for (i=0;i<depth;i++) {putchar(map[stack[i]]); 
//printf("%d\n",k);
}
putchar('\n'); 
} 
else 
{ 
int i; 
for (i=0;i<n;i++) 
if (count[i]) 
{ 
stack[depth]=i; 
count[i]--; 
Find(depth+1); 
count[i]++; 
} 
} 
} 

main() 
{ 
char str[1000]; 
gets(str); 
Make_Map(str); 
Find(0); 
}

------解决方案--------------------
#include <stdio.h>
#define N 6
void putout(int s[],int i);
int put[N];
int count;

int main()
{
int num[N];
int i;
long int number;
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: