全排列

来源:互联网 发布:阿里云手机官网 编辑:程序博客网 时间:2024/05/12 15:19

往下阅读之前,先回想一下深度搜索的思想是什么。因为全排列的递归实现就是应用了深度搜索。

二、应用举例


1. 组合问题

问题表述
口口口 + 口口口 = 口口口 ,将数字1~9分别填入9个口中,每个数字只能使用一次,并使得等式成立。例如,173 + 286 = 459就是一个合理的组合,请问一共有多少种合理的组合呢?注意:173+286=459与286+173=459是同一种组合。

解析
1、首先列出1~9的所有全排列
2、对于每一个排列,判断一次是否满足 a + b == c ?

/*    全排列的应用举例 1    作者:Zoo    时间:2016年4月19日09:14:33*/#include <algorithm> // for copy#include <iostream>  // for cout#include <iterator>  // for ostream_iteratorusing namespace std;int book[10] = { 0 };int res[10];int sum = 0;void dfs(int step, int len){    if (step == len)    {        int a = res[1] * 100 + res[2] * 10 + res[3];        int b = res[4] * 100 + res[5] * 10 + res[6];        int c = res[7] * 100 + res[8] * 10 + res[9];        if (a + b == c)        {            sum++;            cout << a << " + " << b << " = " << c << endl;        }    }    for (int i = 1; i < len; i++)    {        if ( book[i] == 0)        {            res[step] = i;  //            book[i] = 1;            dfs(step + 1, len);            book[i] = 0;        }    }}int main(){    dfs(1, 10);    cout << sum / 2<< endl;    return 0;}

结果如下:

这里写图片描述

三、STL 排列算法


C++ STL 中关于排列的算法有: next_permutation、prev_permutation。

1. next_permutation

用于生成比上一次greater的一次排列。[first,last) 用于指定排列的区间。

函数原型:

bool next_permutation (BidirectionalIterator first,                       BidirectionalIterator last);

示例:

    vector<int> arr;    arr.push_back(1);    arr.push_back(2);    arr.push_back(3);    do    {        copy(arr.begin(), arr.end(), ostream_iterator<int>(cout, ""));        cout << endl;    }while (next_permutation(arr.begin(), arr.end()));

结果:

123132213231312321

2. prev_permutation

与 next_permutation 刚好相反。

0 0