2011-01-10 63 views
3

喜 我用C++工作,可以找到簡單的方法用於從一組含有 EX之間的所有可能的組合數得到一個數組:{1,2,3}獲得從數字的所有組合而不重複

{ {3,1,2}, 
    {1,2,3}, 
    {3,2,1}, 
    {1,3,2}, 
    {2,1,3}, 
    {2,3,1} 
    }; 

問題如果我得到5個或更多數字如何使有120組合

+1

你在找什麼叫「powerset」,因此這是[組合算法]的副本(http://stackoverflow.com/questions/2506119/combinations -algorithm) – 2011-01-10 03:31:44

回答

7

這些是排列,而不是組合。

您可以使用std::next_permutation來計算序列的所有排列。它會是這個樣子:

std::array<int, 3> data = { 1, 2, 3 }; 
do { 
    // use current permutation 
} while (std::next_permutation(data.begin(), data.end())); 

(我用std::array從的C++ 0x在這個例子中,你還可以找到array容器C++ TR1和加速該算法也適用於任何容器。這是雙向迭代,如std::vector。)

相關問題