C++ 递归嵌套for循环在运行时实现特定排列

C++ 递归嵌套for循环在运行时实现特定排列,c++,recursion,C++,Recursion,我正在尝试编写一个递归函数,它实现了n个嵌套for循环,其中n是在运行时确定的,它给出了所有可能的数字1-x的组合。对于x=3,这就是 1 1 1 1 1 2 1 1 3 1 2 1 1 2 2 1 2 3 1 3 1 1 3 2 1 3 3 2 1 1 2 1 2 2 1 3 2 2 1 2 2 2 2 2 3 2 3 1 2 3 2 2 3 3 3 1 1 3 1 2 3 1 3 3 2 1 3 2 2 3 2 3 3 3 1 3 3 2 3 3 3 我希望每一个排列都被保存到一个向量中。

我正在尝试编写一个递归函数,它实现了n个嵌套for循环,其中n是在运行时确定的,它给出了所有可能的数字1-x的组合。对于x=3,这就是

1 1 1
1 1 2
1 1 3
1 2 1
1 2 2
1 2 3
1 3 1
1 3 2
1 3 3
2 1 1
2 1 2
2 1 3
2 2 1
2 2 2
2 2 3
2 3 1
2 3 2
2 3 3
3 1 1
3 1 2
3 1 3
3 2 1
3 2 2
3 2 3
3 3 1
3 3 2
3 3 3
我希望每一个排列都被保存到一个向量中。 关于如何将嵌套for循环实现为递归函数,我已经找到了很多答案,但没有一个能产生我想要的结果。然后是一些答案,这些答案只适用于硬编码的for循环,而我就是不能动态地工作(数量在运行时决定)。然后是一些答案,其中一个排列每一个数字只有一个,这是我不想要的(我也需要像2-2-2或3-3-3这样的排列)。 这似乎是个很简单的问题,但我就是想不出来。任何帮助都将不胜感激

void Foo(向量和列表,常量int&n)
void Foo(vector<vector<int>>& list, const int& n)
{
    if(list.empty())
    {
        list.push_back(vector<int>(n,1));
        return Foo(list,n);
    }

    vector<int> entry(list.back());
    for(int i=n-1; i>=0; i--)
    {
        if(entry.at(i) < n)
        {
            entry[i]++;
            list.push_back(entry);

            return Foo(list,n);
        }

        entry[i] = 1;
    }
}

// test case
vector<vector<int>> list;
Foo(list,3);
{ if(list.empty()) { 列表。推回(向量(n,1)); 返回Foo(列表,n); } 向量项(list.back()); 对于(int i=n-1;i>=0;i--) { if(第(i)项中的条目

如果为空,则将int的大小n向量初始化为1。然后每次迭代它都会克隆最后一个条目,并将索引从最低到最高循环,如果小于n则递增,然后递归或重置为1,然后继续到下一个最重要的索引,直到完成为止。

我认为这应该可以做到:

#include <iostream>
#include <vector>

void getPerm(int from, int to, std::vector<int>& curr, std::vector<std::vector<int>>& result) {
    bool alreadySetToOne  = false;
    int  nextFrom = 0;
    if (curr.size() == to) {
        result.push_back(curr);
        return;
    }

    if (from > 1 && !alreadySetToOne) {
        from = 1;
        alreadySetToOne = true;
    }

    for (int i=from; i <= to; ++i) {
        curr.push_back(i);
        getPerm(i, to, curr, result);
        curr.pop_back();
    }
}

int main() {
    auto n = 0;
    std::vector<std::vector<int>> results;
    std::vector<int> curr;
    std::cout << "Put number ...\n";
    std::cin >> n;
    getPerm(1, n, curr, results);


    //Check results
    for (int i=0; i < results.size(); ++i) {
        for (int j = 0; j < results[i].size(); ++j) {
            std::cout << results[i][j] << ", ";
        }
        std::cout << std::endl;
    }
}
#包括
#包括
void getPerm(int-from、int-to、std::vector和curr、std::vector和result){
bool-alreadySetToOne=false;
int nextFrom=0;
如果(当前大小()=到){
结果:推回(当前);
返回;
}
如果(从>1&!开始){
from=1;
alreadysettone=真;
}
for(int i=from;i n;
getPerm(1,n,curr,results);
//检查结果
对于(int i=0;istd::你试过什么了吗?所以不是一个代码编写服务,这不是置换。{1,2,3}的置换将是{1,3,2},{2,3,1},{2,1,3},{3,1,2}和{3,2,1}@user463035818,它们是置换…只是不是你通过应用
std::next\u置换
得到的置换。这些是