生成1~n的全排列,按字典序输出

这个题按照书上的解法,输出顺序并不是字典序,所以在网上找到了一个很棒的解法,先写到这里记录下来。

#include<iostream>
using namespace std;
int a[100];
void dfs(int cur,int n)//cur表示目前正在填的数,n表示总共要填的数 
{
    if(cur==n)//递归边界,说明填完了 
    {
        for(int i=0;i<n;i++)//一个一个的输出 
        cout<<a[i]<<" ";
        cout<<endl;
    }
    for(int i=1;i<=n;i++)//把数字1-n填入 
    {
        int ok=1;
        for(int j=0;j<cur;j++)//遍历目前a数组里面的元素,判断当前这个数有没有填过(用过) 
        {
            if(a[j]==i) ok=0;
        }
        if(ok==1)
        {
            a[cur]=i;//没有填过就填 ,把它放在a数组的最后 
            dfs(cur+1,n);//再排A数组元素里面的第cur+1个位置 (这里就不需要设置撤销的动作了~反正每次进来都会判断数字有没有填过) 
        }
    }
}
int main()
{
    int n;
    cin>>n;
    dfs(0,n);
    return 0;
}

  以上是找到的解法,我自己写的是下面的,但是不能够按照字典顺序输出

#include <iostream>
using namespace std;

template<class type> 
inline void Swap(type & a, type & b)
{
  type temp = a;
  a = b;
  b = temp; 
}

template<class type>
void Perm(type list[],int k, int m)
{
  if(m == k)
  {
    for(int i = 0;i <= m;i++)
      cout << list[i];
    cout << endl;
  }
  else
  {
    for(int i = k;i <= m;i++)
    {
      Swap(list[k], list[i]);
      Perm(list, k+1, m);
      Swap(list[k], list[i]);
    }
  }
}

int main()
{
  int N, num[10];
  cin >> N;
  for(int i = 1, j = 0;i <= N;i++, j++)
  {
    num[j] = i;
  }
  Perm(num, 0, N-1);
  return 0;
}

 



posted @ 2019-03-22 15:16  清酒与僧邂世尘  阅读(1367)  评论(0编辑  收藏  举报