使用stl的next_permutation

函数原型

bool next_permutation (BidirectionalIterator first,BidirectionalIterator last);

函数返回值

true if the function could rearrange the object as a lexicographicaly greater permutation.Otherwise, the function returns. 
false to indicate that the arrangement is not greater than the previous, but the lowest possible (sorted in ascending order).

使用 next_permutation() 输出九宫格。即把 1 9 9 个数字放入一个九宫格中,使得它的横向,竖向,对角线的三个数字之和相等。

#include <iostream>
#include <iomanip>
#include <algorithm>
#include "math.h"
int main(int argc, char* argv[])
{
    int array[10]={0,2,9,4,7,5,3,6,1,8};
    while(std::next_permutation(array+1,array+10))
    {

           if((array[1]+array[2]+array[3])!=15)
                continue;
           if((array[4]+array[5]+array[6])!=15)
                continue;
           if((array[7]+array[8]+array[9])!=15)
                continue;
           if((array[1]+array[4]+array[7])!=15)
                continue;
           if((array[2]+array[5]+array[8])!=15)
                continue;
           if((array[3]+array[6]+array[9])!=15)
                continue;
           if((array[1]+array[5]+array[9])!=15)
                continue;
           if((array[3]+array[5]+array[7])!=15)
               continue;
           std::cout<<array[1]<<"\t"<<array[2]<<"\t"<<array[3]<<std::endl;
           std::cout<<array[4]<<"\t"<<array[5]<<"\t"<<array[6]<<std::endl;
           std::cout<<array[7]<<"\t"<<array[8]<<"\t"<<array[9]<<std::endl<<std::endl;
    }          
    return 0;
}
输出结果为

使用stl的next_permutation_第1张图片

输出结果有6个,其实实质是1个,然后不同角度旋转之后形成了6个结果。


你可能感兴趣的:(使用stl的next_permutation)