Combinations

Intro

Combination is a way of selecting items from a collection. The order of selection doesn't matter. For example, there's a collection of three fruits {apple,orange,pear}\{apple, orange, pear\} for breakfast. You can only pick two of them. You can pick {apple,orange}\{apple, orange\}, {apple,pear}\{apple, pear\}, or {orange,pear}\{orange, pear\}.

Question (LC.77)

Given two positive integers n and k, return all possible combinations of size k from [n].

Example

What if n < 1 or k < 1 or n < k? Empty list How large is the input size? k is less than 10

Analysis

Finding all possible combinations requires an exhaustive search. Backtracking will be handy for enumeration problems like this. One thing worth noting is that the order does not matter for combinations. We want to use a strictly increasing order to eliminate duplicate combinations. For example, [1,2,3] can represent all other permutations from it [1,3,2], [2,1,3], [2,3,1], [3,1,2], etc. The order does not matter here because there's only one order.

Note: Strictly increasing is made possible by the condition that each integer/element can only be used at most once.

Approach

Code

Time Complexity

Time = #combinations * O(k) = O(n choose k) * O(k)

Last updated