c++中的全排列函数next_permutation()
生活随笔
收集整理的這篇文章主要介紹了
c++中的全排列函数next_permutation()
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
全排列函數next_permutation()
prev_permutation函數(按降序排序)
計算序列全排列的函數:next_permutation(start,end),此函數求的是當前排列的下一個排列,這里的“下一個”,我們可以把它理解為序列的字典序的前后
此外,還應該注意的是,next_permutation()在使用前需要對欲排列數組按升序排序,否則只能找出該序列之后的全排列數。
next_permutation函數詳解:
組合數學中經常用到排列,這里介紹一個計算序列全排列的函數:next_permutation(start,end),和prev_permutation(start,end)。這兩個函數作用是一樣的,區別就在于前者求的是當前排列的下一個排列,后一個求的是當前排列的上一個排列。至于這里的“前一個”和“后一個”,我們可以把它理解為序列的字典序的前后,嚴格來講,就是對于當前序列pn,他的下一個序列pn+1滿足:不存在另外的序列pm,使pn<pm<pn+1.
對于next_permutation函數,其函數原型為:
#include <algorithm>bool next_permutation(iterator start,iterator end)當當前序列不存在下一個排列時,函數返回false,否則返回true
#include <iostream> #include <algorithm> using namespace std; int main() {int a[3]={1,2,3};while(next_permutation(a,a+3)){cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;}return 0; }
可能你會發現并沒有輸出1 2 3,這就可以用它的概念(性質)來回答了。
如果想要全部輸出,可以考慮用do語句
#include <iostream> #include <algorithm> using namespace std; int main() {int num[3]={1,2,3};do{cout<<num[0]<<" "<<num[1]<<" "<<num[2]<<endl;}while(next_permutation(num,num+3));return 0; }
參考原文全排列函數next_permutation()
prev_permutation函數
總結
以上是生活随笔為你收集整理的c++中的全排列函数next_permutation()的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 老玩家却这么玩为什么老玩家
- 下一篇: c++牛客网面试题05. 替换空格