生成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;
}

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM