数组的排列 [英] Permutation of array
本文介绍了数组的排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如我有这个数组:
int a[] = new int[]{3,4,6,2,1};
我需要所有排列的列表,如果一个是这样的,{3,2,1,4,6}
,其他的一定不一样.我知道如果数组的长度是 n 那么有 n! 可能的组合.这个算法怎么写?
I need list of all permutations such that if one is like this, {3,2,1,4,6}
, others must not be the same. I know that if the length of the array is n then there are n! possible combinations. How can this algorithm be written?
更新:谢谢,但我需要一个伪代码算法,如:
Update: thanks, but I need a pseudo code algorithm like:
for(int i=0;i<a.length;i++){
// code here
}
只是算法.是的,API 函数很好,但对我帮助不大.
Just algorithm. Yes, API functions are good, but it does not help me too much.
推荐答案
如果你使用 C++,你可以使用 std::next_permutation
来自
头文件:
If you're using C++, you can use std::next_permutation
from the <algorithm>
header file:
int a[] = {3,4,6,2,1};
int size = sizeof(a)/sizeof(a[0]);
std::sort(a, a+size);
do {
// print a's elements
} while(std::next_permutation(a, a+size));
这篇关于数组的排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文