n個整數全排列的遞迴實現(C++),遞迴

來源:互聯網
上載者:User

n個整數全排列的遞迴實現(C++),遞迴

 全排列是非常常用的一個小演算法,下面是n個整數全排列的遞迴實現,使用的是C++


#include <iostream>using namespace std;int n = 0;void swap(char *a ,char *b){int m ;m = *a;*a = *b;*b = m;}void perm(char list[],int k, int m ){int i;if(k >m){for(i = 0 ; i <= m ; i++){cout<<list[i];}cout<<endl;}else{for(i = k ; i <=m;i++){swap(&list[k],&list[i]);perm(list,k+1,m);swap(&list[k],&list[i]);}}}int main(){char list[] ="12345";perm(list,0,4);return 0;}



C++編寫程式,輸入數n,輸出n個字元的全排列,通過函數遞迴實現

#include <iostream>using namespace std;void output(char d[],int n) // 輸出{ for (int i=0;i<n;i++) cout<<d[i]; cout<<" ";}void swap(char &x, char &y) //交換{char t = x;x = y;y = t;}void perm(char d[],int n,int j) // j起始下標{ if (j==n) output(d,n); // 輸出 else for (int i=j;i<n;i++) { if (i!=j) swap(d[j],d[i]); // 交換 perm(d,n,j+1); //遞迴求排列 if (i!=j) swap(d[j],d[i]);} // 恢複 }int main(){char a[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};int n;cout<<"請輸入n:\n";cin>>n;perm(a,n,0);cout<<endl;system("pause");return 0;}演算法:1.將第一個字元,依次與後n-1個字元交換值,每次交換得到一個新的首字母; 2.剩下的n-1個字母按1步驟重複直至所有數組完成排列;

 
C++代碼 遞迴演算法 n個數的全排列 (是任意的,可不連續) 要: 提示輸入數的個數n 然後提示輸入這n個

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
using namespace std;
const int MAX=10;
int a[MAX],b[MAX];
bool used[MAX]={false};
void DFS(int deep,int n)
{
int i;
if(deep==n)
{
for(i=0;i<n;i++)cout<<b[i]<<" ";
cout<<endl;
return ;
}
for(i=0;i<n;i++)
{
if(used[i])continue;
used[i]=true;
b[deep]=a[i];
DFS(deep+1,n);
used[i]=false;
}
}
int main()
{
int n,i;
cin>>n;
for(i=0;i<n;i++)cin>>a[i];
DFS(0,n);
return 0;

}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.