一、模板
c++的algorithm庫裡面有乙個函式next_permutation(start,end)。作用就是求乙個排序的下乙個排列,可以遍歷全排列。注意如果不結束會一直迴圈,結果出現相同的排列。與之完全相反的函式還有prev_permutation(start,end),就是求乙個排序的上乙個排列的函式。
對於next_permutation函式,其函式原型為:
include
bool next_permutation(iterator start, iterator end)
// 當前序列不存在下乙個排列時,函式返回false,否則返回true。
#include
using
namespace std;
int n;
// n表示序列中數的個數
int a[
10005];
intmain()
while
(next_permutation
(a, a + n));
return0;
}
需要強調的是,next_permutation()在使用前需要對欲排列陣列按公升序排序,否則只能找出該序列之後的全排列數。
非模板//z這個**對應的乙個例題
#include
int cnt=0;
using
namespace std;
typedef
long
long ll;
const
int maxn=
1e6+
199;
int len1,len2,len3;
ll a[maxn]
;int k,n,m;
void
dop(
)for
(int i = n; i > k; i--)}
sort
(a + k +
1, a + n +1)
;//對後面的公升序排列
}int
main()
for(
int i=
1;i<=n;i++
)return0;
}
全排列 模板和例題
1.直接使用 stl 中的 next permutation 實現全排列 includeusing namespace std intmain sort a,a 4 do printf n while next permutation a,a 4 2.遞迴求全排列 n 個元素的全排列 不斷將每個元素...
簡單dfs模板 luogu全排列問題
emmmm我也想了很久才做出來好吧 作為乙個瘋狂練搜尋的小菜雞 題目描述 輸出自然數 11 到 nn 所有不重複的排列,即 nn 的全排列,要求所產生的任一數字序列中不允許出現重複的數字。輸入格式 乙個整數 nn。輸出格式 由 1 n 組成的所有不重複的數字序列,每行乙個序列。每個數字保留 55 個...
全排列 非遞迴
description 列出所有數字1到數字n的連續自然數的排列,要求所產生的任一數字序列中不允許出現得復數字。input 輸入 n 1 n 9 output 由1 n組成的所有不重複的數字序列,每行乙個序列。sample input 3 sample output 1 2 3 1 3 2 2 1 ...