1

我需要 c++ 代码,它将生成所有可能的组合(n,k),其中 n - 输入数组中的整数个数。k - 位置数

例如 输入:

n = [1 2 3];
k = 2;

输出:

A3 =

     1     1
     1     2
     1     3
     2     1
     2     2
     2     3
     3     1
     3     2
     3     3

谢谢。

4

3 回答 3

3

使用标准库

do {
    for(int i = 0; i < k; i++){
        std::cout << n[i];
    }
    std::cout << '\n';
} while (std::next_permutation(n, n + k));
于 2012-04-07T13:16:20.003 回答
1

这基本上是以 n-1 为底数(每个数字都移动 1),请尝试以下操作:

编辑:用来vector代替new[],delete[]

#include <vector>

void generatePerms(int n, int k)
{
    vector<int> perms(k, 1);

    //iterate through all permutations
    bool done;
    do {
        //Do something with the current permutation, for example print it:
        for (int i = 0; i < k-1; i++)
            cout << perms[i] << ", ";
        cout << perms[k-1] << endl;

        /*
         * Increment last digit first - if it's to big, reset to 1 and
         * carry one (increment next digit), which may also carry one etc.
         *
         * If all digits caused a carry, then the permutation was n, n, ..., n,
         * which means, that we can stop.
         */
        done = true;
        for (int i = k-1; i >= 0; i--) {
            if (++perms[i] > n) {
                perms[i] = 1;
                continue;
            } else {
                done = false; //not all digits caused carry
                break;
            }
        }
    } while (!done);
}
于 2012-04-07T12:50:28.140 回答
1

在这里查看我的答案:

PHP 采取所有组合

这是PHP;但是这个概念(递归等)应该很容易“翻译”......

于 2012-04-07T12:56:13.703 回答