Generate all possible combinations in 0, 1,...n-1, n of k numbers. Each combination should be in ascending order

1.1k views Asked by At

Please understand that this is not a duplicate question. This question needs sorted combinations. Please read the question before. The combination can have repeats of a number. Currently, i have tried generating permutations of n-k+1 0s and k 1s. But it does not produce the combinations with repeats. For example: Choosing 3 numbers from 0, 1,....n, it generates 9 combinations:

(0 1 2),
(0 1 3),
(0 1 4),
(0 2 3),
(0 3 4),
(1 2 3),
(1 2 4),
(1 3 4),
(2 3 4)

I need it include these combinations too:

(0, 0, 0),
(0, 0, 1),
(0, 0, 2),
(0, 0, 3),
(0, 0, 4),
(0, 1, 1),
(0, 2, 2),
(0, 3, 3),
(0, 4, 4),
(1, 1, 1),
(1, 1, 2),
(1, 1, 3),
(1, 1, 4),
(1, 2, 2),
(1, 3, 3),
(1, 4, 4),
(2, 2, 2),
(2, 2, 3),
(2, 2, 4),
(2, 3, 3),
(2, 4, 4),
(3, 3, 3),
(3, 3, 4),
(3, 4, 4),
(4, 4, 4)

What's the most efficient way to get this result? I have used next_permutation to generate the combination right now. Take a look please:

    vector<ll> nums, tmp;
    for(i = 0; i <= m - n; i++)
    {
        nums.push_back(0);
    }
    for(i = 0; i < n; i++)
    {
        nums.push_back(1);
    }
    do 
    {
        tmp.clear();
        for(i = 0; i <= m; i++)
        {
            if(nums[i] == 1)
            {
                tmp.push_back(i);
            }
        }
        for(i = 0; i < tmp.size(); i++)
        {
            cout << tmp[i] << " ";
        }
        cout << endl;
    } while(next_permutation(nums.begin(), nums.end()));
2

There are 2 answers

0
MBo On

Your 'combinations' are essentially k-digit numbers in base-N numeral system. There are N^k such numbers.

The simplest method to generate them is recursive.

You can also organize simple for-cycle in range 0..N^k-1 and represent cycle counter in the mentioned system. Pseudocode

for (i=0; i<N^k; i++)  {  //N^k is Power, not xor
   t = i 
   d = 0
   digit = {0}
   while t > 0 do {
      digit[d++] = t%N //modulus
      t = t / N    //integer division
   }
   output digit array
}
1
Jarod42 On

Following may help:

bool increment(std::vector<int>& v, int maxSize)
{
    for (auto it = v.rbegin(); it != v.rend(); ++it) {
        ++*it;
        if (*it != maxSize) {
            return true;
        }
        *it = 0;
    }
    return false;
}

Usage:

std::vector<int> v(3);

do {
    // Do stuff with v
} while (increment(v, 10));

Live demo