DFS 通过交换元素顺序实现全排列

来源:互联网 发布:生存兽帝数据 编辑:程序博客网 时间:2024/06/06 00:28
// DFS.cpp : Defines the entry point for the console application.//#include "stdafx.h"  #include "stack"  #include "stdio.h"  #include "iostream"  #include "vector"    using namespace std;  vector<int> vec;  vector<int> vec2;  stack<int> s;    void DFS(int k, int num);void DFS2();  void DFS3(int in, int out);void DFS4(int k, int num);void SWAP(vector<int> &vec, int i, int j);  int _tmain(int argc, _TCHAR* argv[])  {      //DFS(0);      //vec[0] = 5;      for (int i = 0;i<5;i++)      {          vec.push_back(i+1);      }    //DFS4(0,5);  DFS(0, 5);    system("pause");      return 0;  }void SWAP(vector<int> &vec, int i, int j){int temp = vec[i];vec[i] = vec[j];vec[j]= temp;}// 通过交换元素的思想,实现全排列void DFS(int k, int num){if( k == num ){// 输出可能存在的出栈顺序for(int i =0; i<vec.size(); i++)printf("%4d", vec[i]);printf("\n");return;}else{// 通过交换实现全排列for( int i = k; i<vec.size(); i++){SWAP(vec, k, i);DFS(k+1,num);SWAP(vec, i, k); // 交换回去}}}



原创粉丝点击