數字每一個數字可能我有以下陣列:
int a[3]={1, 2, 3};
注:我不知道數組有多少個元素了。
試圖與來自陣列
我要輸出
123; 132; 213; 231; 312; 321.
但是我不知道在該數組中找到了多少個數字。同樣的數字也不能重複。
數字每一個數字可能我有以下陣列:
int a[3]={1, 2, 3};
注:我不知道數組有多少個元素了。
試圖與來自陣列
我要輸出
123; 132; 213; 231; 312; 321.
但是我不知道在該數組中找到了多少個數字。同樣的數字也不能重複。
所以它的不斷變化。你有N! permuations。
遞歸地編寫函數最簡單,列舉第一個數字,然後從N-1開始,然後從N-2開始,第三個從N-2開始依此類推。
正如評論說,這聽起來像你想std::next_permutation,這裏是如何使用它:
int main()
{
std::vector<int> a{ 1, 2, 3 };
std::sort(a.begin(), a.end());
do {
std::cout << a << "; ";
} while (std::next_permutation(a.begin(), a.end()));
return 0;
}
請注意,你需要的operator<<()
過載:
std::ostream& operator<<(std::ostream& s, const std::vector<int>& v)
{
for (auto&& item : v)
s << item;
return s;
}
這個程序的輸出是
123; 132; 213; 231; 312; 321;
你甚至可以做一個小工具程序:
void permutations(std::ostream& s, std::vector<int> a)
{
std::sort(a.begin(), a.end());
do {
s << a << "; ";
} while (std::next_permutation(a.begin(), a.end()));
}
permutations(std::cout, a);
std::cout << "\n";
permutations(std::cout, { 3, 1, 4, 2 });
如果你真的寫C++,你「不知道數組有多少個元素了,」你應該使用'標準::矢量 a {1,2,3};'。在任何情況下,所寫的問題都是針對SO的OT,詳情請參見[mcve]。 –
您可能正在尋找['std :: next_permutation'](http://en.cppreference.com/w/cpp/algorithm/next_permutation) –