2013-03-09 75 views
1

我試圖解決一些UVA的問題,我想生成一個字符串數組的所有可能的組合。例如:生成字符串矢量的所有組合

string str[]={"abcd","efg","hij"}; 

所以程序必須打印:

>abcd efg hij 
    >abcd hij efg 
    >hij abcd efg 
    >hij efg abcd 
    >efg abcd hij 
    >efg hij abcd 
+0

你還需要打印涉及陣列中的所有項目並非排列,如'EFG hij','HIJ efg',和'hij',比如? – angelatlarge 2013-03-09 19:17:02

+0

你想排列,而不是組合。 – stackoverflowuser2010 2013-03-09 20:38:37

回答

1

我認爲你正在尋找STL的next_permutation算法。

適用於您的例子,它應該是這個樣子:

std::sort (str, str+3); 

std::cout << "The 3! possible permutations with 3 elements:\n"; 
do { 
    std::cout << str[0] << ' ' << str[1] << ' ' << str[2] << '\n'; 
} while (std::next_permutation(str, str+3)); 
+0

爲什麼在循環之前調用std :: sort()。在這種情況下需要嗎?因爲我們正在尋找數組中所有字符串的排列方式,所以在這種情況下需要預先排序? – goldenmean 2013-03-11 11:58:47

+0

我相信算法會根據元素是否排序來確定它是否完成。因此,如果您之前未對其進行排序,則可能無法獲得所有排列,因爲算法認爲排序後就完成了排列。 – tehlexx 2013-03-11 13:07:52