Looking at your comments on the original post, you want an iterative solution. A recursive solution will be as fast as an iterative solution if you have a language that supports tail call optimization. But if you are working with Java / C #, again, this is not available, so thereβs another way to look at the problem.
You generate combinations. A combination is simply a subset with a certain number of elements. Subsets with small units can be expressed in bits.
If I have a set of [1, 2, 3, 4] , and I want to describe a subset of [1, 3, 4] , I can do this by going through each element and setting "True or False: is this element in the subset?". So, for [1, 3, 4] result is [True, False, True, True] . If I work with a set of less than 32 (or 64) bytes, I can encode this as an integer: 1011b = 11. It is very compact in memory, and computers usually have very fast bitmate operators.
So what is a combination, in terms of these binary numbers? If I want all subsets with N members, I can translate this as "I want all numbers with the N bits set."
Take [1, 2, 3, 4] as we were. We want all subsets with three elements. How many 4-bit numbers are there with 3 bits? Answer: 1110b, 1101b, 1011b and 0111b. If we translate these integers into subsets, we get your solutions: [1, 2, 3] , [1, 2, 4] , [1, 3, 4] and [2, 3, 4] .
You can start thinking only by bits. You start with the smallest number with the N bits set. This is consistent with the decision. Then you start flipping bits one by one. Systematically, so that each iteration always leads to the next largest number.