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