C/C++ | 全排列 | next_permutation | prev_permutation | 常规全排列

版权声明:本人小白,有错误之处恳请指出,感激不尽;欢迎转载 https://blog.csdn.net/stone_fall/article/details/88670531

全排列

next_permutation

这里一般先用快排sort对原有数组进行排序

// next_permutation example
#include <iostream>     // std::cout
#include <algorithm>    // std::next_permutation, std::sort, std::reverse
using namespace std;
int main () {
  int myints[] = {1,2,3};

  sort (myints,myints+3);
  reverse (myints,myints+3);

  cout << "The 3! possible permutations with 3 elements:\n";
  do {
    cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
  } while ( std::prev_permutation(myints,myints+3) );

  scout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';

  return 0;
}

输出

The 3! possible permutations with 3 elements:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
After loop: 1 2 3

prev_permutation

sort排序后用reverse进行翻转

// next_permutation example
#include <iostream>     // std::cout
#include <algorithm>    // std::next_permutation, std::sort, std::reverse
using namespace std;
int main () {
  int myints[] = {1,2,3};

  sort (myints,myints+3);
  reverse (myints,myints+3);

  cout << "The 3! possible permutations with 3 elements:\n";
  do {
    cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
  } while ( std::prev_permutation(myints,myints+3) );

  cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';

  return 0;
}

输出

3 2 1
3 1 2
2 3 1
2 1 3
1 3 2
1 2 3
After loop: 3 2 1

递归全排列

void perm(int arr[], int begin,int end){
    {
    //这里进行赋值或者输出操作
    }
    for(int j=begin;j<=end;j++){    
        swap(begin,j);        //for循环将begin~end中的每个数放到begin位置中去
        perm(arr,begin+1,end);    //假设begin位置确定,那么对begin+1~end中的数继续递归
        swap(begin,j);        //换过去后再还原
    }
}

 

猜你喜欢

转载自blog.csdn.net/stone_fall/article/details/88670531