试图用数组的数字使所有数字可能

Trying to make every number possibility with digits from array

本文关键字:数字 数组      更新时间:2023-10-16

我有以下数组:
int a[3]={1, 2, 3};
注意:我不知道该数组有多少个元素。

我想输出

123;132;213;231;312;321。

但是,我不知道阵列中有多少位数字。同样的数字也无法重复。

正如评论所说,听起来您想要std :: next_permunt,这是使用它的方法:

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 });

,因此它永远存在。你有n!置换。

最容易递归地写出该函数,列举第一个数字,然后从N-1中获得第二位,第三位来自N-2等。