#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<Windows.h>
using namespace std;
int main()
{
int n;
while(cin>>n){
if(n==0)break;
DWORD start_time=GetTickCount();
char str[15];
memset(str,0,sizeof(0));
for(int i=1;i<=n;i++){
str[i]=i+48;
}
for(int j=1;j<=n;j++){
cout<<str[j];
}
cout<<endl;
while(next_permutation(str+1,str+n+1)){
for(int j=1;j<=n;j++){
cout<<str[j];
}
cout<<endl;
}
DWORD end_time=GetTickCount();
cout<<"The run time is:"<<end_time-start_time<<"ms!"<<endl;
}
return 0;
}
java代码:
/**
* 递归 时间复杂度O(n!)
* 思路:
* 1.若序列长度n=1,则输出当前序列结束。
* 2.否则
* 2.1i=0,...n-1与第n个元素交换
* 2.2.对于前n-1长度序列,循环步骤1,2.(递归n-1长度序列)
* @param arr
* @param len
* @param num
* @return
*/
public static void iterationLoopArray(int[] arr,int len){
if(len==1){
printArray(arr); //打印当前序列
count++;
}else{
for(int i=0;i<len;i++){
int temp=arr[i];
arr[i]=arr[len-1];
arr[len-1]=temp;
iterationLoopArray(arr,len-1); //递归调用len-1长度序列
//swap(arr,arr[len-1],i);
temp=arr[i];
arr[i]=arr[len-1];
arr[len-1]=temp;
}
}
}
/**
* 打印数组
* @param arr
*/
public static void printArray(int[] arr){
String s="";
for(int i=0;i<arr.length;i++){
s=s+arr[i]+" ";
}
System.out.println(s);
}
http://blog.csdn.net/qq_33362864/article/details/51884270?locationNum=2&fps=1
#include<iostream>
using namespace std;
void Permutation(char* pStr, char* pBegin);
void permutation(char* pStr)
{
Permutation(pStr, pStr);
}
void Permutation(char* pStr, char* pBegin)
{
if(!pStr || !pBegin)
return;
if(*pBegin == '\0')
{
printf("%s\n", pStr);
}
else
{
for(char* pCh = pBegin; *pCh != '\0'; ++ pCh)
{
// swap pCh and pBegin
char temp = *pCh;
*pCh = *pBegin;
*pBegin = temp;
Permutation(pStr, pBegin + 1);
// restore pCh and pBegin
temp = *pCh;
*pCh = *pBegin;
*pBegin = temp;
}
}
}
int main()
{
char str[] ={'1','2','3','\0'};
permutation(str);
getchar();
return 0;
}
刚刚没有采用代码片,没有显示头文件,不好意思~orz
我的代码后面有程序测试时间,可以比较直观的观察程序run的时间,输入0的时候程序结束。