// TotalOrder.cpp : Defines the entry point for the console application.
//各位见笑了,哥们算法太烂,多多指教
#include “stdafx.h”
#include <iostream>
#include <stack>
using namespace std;
typedef struct bia{
int Value;
int Position;
}assist;
typedef struct ord{
int loc_i;
int loc_j;
}location;
void TotalOrder1(int*src,int*bia_src,int*result,int k,int n)
{//不能去除重复排列 递归回溯
if (k==n)
{
for (int i=0;i<n;i++)
{
cout<<result[i];
}
cout<<endl;
return;
}
for (int i=0;i<n;i++)
{
if(!bia_src[i])
{
bia_src[i]=1;
result[k]=src[i];
TotalOrder1(src,bia_src,result,k+1,n);
bia_src[i]=0;
}
}
}
void TotalOrder2(int*src,int*bia_src,assist*result,int k,int n)
{//有重复值时删去重复序列 递归回溯
int state=1;
if (k==n)
{
for (int i=0;i<n;i++)
{
cout<<result[i].Value;
}
cout<<endl;
return;
}
for (int i=0;i<n;i++)
{
if(!bia_src[i])
{
for (int j=0;j<k;j++)
{
if ((result[j].Value==src[i])&&(result[j].Position>i))return;
}
bia_src[i]=1;
result[k].Value=src[i];
result[k].Position=i;
TotalOrder2(src,bia_src,result,k+1,n);
bia_src[i]=0;
}
}
}
void print(int *res,int n){
for (int i=0;i<n;i++)
{
cout<<res[i];
}
cout<<endl;
}
void TotalOrder3(int *src,int *bia_src,int *result,int N)
{//非递归版本
int state=0;
stack<location> st;
location temp;
temp.loc_j=-1;
temp.loc_i=0;
int i,j;
for(i=0;i<N;i++)
{
for(j=temp.loc_j+1;j<N;j++)
{
if(!bia_src[j])
{ state=1;
result[i]=src[j];
bia_src[j]=1;
temp.loc_i=i;
temp.loc_j=j;
st.push(temp);
break;
}
}
if (i==N-1)
{ if (state)
{
print(result,N);
state=0;
}
if (st.empty())break;
else{
temp=st.top();
st.pop();
i=temp.loc_i-1;
bia_src[temp.loc_j]=0;
}
}
else if(state)
{
temp.loc_j=-1;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int n=3;
int *src=(int*)malloc(sizeof(int)*n);
memset(src,0,sizeof(int)*n);
int *bia_src=(int*)malloc(sizeof(int)*n);
memset(bia_src,0,sizeof(int)*n);
int *result=(int*)malloc(sizeof(int)*n);
memset(result,0,sizeof(int)*n);
for(int i=0;i<n;i++)
{
src[i]=i+1;
}
//TotalOrder1(src,bia_src,result,0,n);
TotalOrder3(src,bia_src,result,n);
return 0;
}