求一個全排列,用遞歸的思想來解決,在看遞歸的問題的時候,如果考慮所有分支條件,發現非常不適合,那麼如何有效的分析遞歸的程序呢。1.遞歸需要遞歸出口 2.遞歸絕對擁有根自身一樣性質的子問題,下面用求全排列的代碼來看看這個問題,關於類似的問題還有八皇后,棋盤問題,遞歸方法求逆序等等。。
/*************************************************************************
ID:panzhiz1
PROG:permutation
LANG:C++
Created Time: 2014/3/21 13:25:22
************************************************************************/
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<fstream>
using namespace std;
template<class T>
void permutation(T array[],int begin,int end){
if(begin==end){
for(int i=0;i<=end;i++){
cout<<array[i]<<" ";
}
cout<<endl;
}
else{
for(int i=begin;i<=end;i++){
swap(array[i],array[begin]);
permutation(array,begin+1,end);
swap(array[i],array[begin]);
}
}
}
int main(){
int arr[]={
1,2,3,4,5
};
permutation(arr,0,4);
system("pause");
return 0;
}