打印固定数量的整数的所有置换,总计为k

时间:2018-12-03 22:54:51

标签: c++ recursion sum permutation

假设我有一个大小为./msg bot send nick #<show>. (New.Amsterdam.2018.S01E09.1080p.WEB.H264.METCON)的0初始化的数组。

我想打印n个正整数的所有排列,加起来等于一个正整数n

目前,我的代码仅打印一些排列(正确的排列,但仍然缺少一些排列)。

例如,对于kn = 4,我的代码正在打印:

k = 3

您可以看到它缺少一些排列。例如:1 1 1 0 1 1 0 1 1 0 2 0 1 0 1 1 1 0 1 1 1 0 0 2 0 2 1 0 0 2 0 1 0 1 2 0 0 1 1 1 0 1 1 1 0 1 0 2 0 1 2 0 0 1 1 1 0 0 3 0 0 0 2 1 0 0 2 1 0 0 1 2 0 1 1 1 0 1 0 2 0 0 2 1 0 0 1 2 0 0 1 2 0 0 0 3 3 0 0 0等。

代码:

0 3 0 0

2 个答案:

答案 0 :(得分:0)

您只需一次递增a[0] ,因为只有第一个调用printAll的{​​{1}}值为0。beg可以是增加两次,a[1]增加3次,等等。

您需要更改a[2]中的循环,才能多次递增printAll

答案 1 :(得分:0)

万一将来有人需要...

我遵循Thomas Matthews的建议,并开始寻找显示所有排列(带有重复)的解决方案。

我发现this answer正是这样做的。我只需要修改一下我的代码,它现在就可以正常工作。

#include <iostream>
#include <vector>

template <class Iter>
bool next_variation(Iter first, Iter last, const typename std::iterator_traits<Iter>::value_type max){
    if(first == last) return false;
    Iter i(last); --i;
    if(*i < max) { ++(*i); return true; }
    while( i != first ){
        *i = 0;
        --i;
        if(*i < max) { ++(*i); return true; }
       }
    return false;
}

void printVector(std::vector<int> a){
    for(std::vector<int>::const_iterator it = a.begin(); it!= a.end(); ++it)
        std::cout << *it << " ";
    std::cout << std::endl;
}

int currentSum(std::vector<int> a){
    int sum = 0;
    for(std::vector<int>::const_iterator it = a.begin(); it!= a.end(); ++it)
        sum += *it;
    return sum;
}

void printAll(std::vector<int> a, int k){
    do{
        if(currentSum(a) == k)
            printVector(a);
      }
    while( next_variation(a.begin(), a.end(), a.size()) );
}

int main(){
    int k = 3; //array must add up to k, exactly
    int arraySize = 4;

    std::vector<int> a(arraySize,0); // Initialized with 0
    printAll(a, k);

}

输出为:

0 0 0 3
0 0 1 2
0 0 2 1
0 0 3 0
0 1 0 2
0 1 1 1
0 1 2 0
0 2 0 1
0 2 1 0
0 3 0 0
1 0 0 2
1 0 1 1
1 0 2 0
1 1 0 1
1 1 1 0
1 2 0 0
2 0 0 1
2 0 1 0
2 1 0 0
3 0 0 0

符合预期。