This is a nice complete search problem. This problem asks us to print all size $6$ combinations of a subset whose size is $k$ and $6 < k < 13$.
As there can be at most $\dbinom{12}{6} = 924$ combinations, complete search will not exceed the time limit in this case.
We can use $6$ nested loops to traverse the complete search space. Let’s see the implementation in C++
:
So what is going on here? Let’s break it down!
In each of the for
loop, we’re only taking one element and leaving the rest of choices to nested for
loops.
Before the first for
loop, we haven’t chosen any element. So, in the first for loop, we can iterate until index $i$, such that the range $\big[i,n\big)$ is large enough to choose $6$ elements.
Let’s take an example. Say, we have a subset $s$ with the following $7$ numbers:
$\textrm{1 2 3 4 5 6 7}$
So, we can iterate up to $i = 1$ in the first for
loop. Because when $i = 1$, the range $\big[i, n\big)$ is large enough to contain $6$ elements. If we proceed further, for example to $i = 2$, then there will be $ 7 - 2 = 5$ elements left and from these $5$ elements we’ll have to choose $6$ (which is impossible). So, we can iterate only up to $i = 1$ in the first for
loop.
Similar reasoning can be applied for the rest of the nested for
loop. In each case, we can iterate only until there’s enough element left to ensure the choosing of the remaining elements. For example, in the second for
loop, we start from $i + 1$ (which means that we have chosen $s[i]$), and we iterate until the remaining array is long enough to contain $5$ elements.
We iterate until we’ve chosen $6$ elements. Once we’ve chosen $6$ elements, then we have a valid combination. Also notice we’re printing combinations in lexicographical order. Because in each step, we’re only choosing elements that precede others in order. As the input is already sorted, we choose the lowest number first, then the second lowest number and so on as we’re iterating from left to right.
Also be careful not to print an extra blank after the last test case!
Sharing is caring. Share this story in...
Share: Twitter Facebook LinkedIn