Combinations - Problem

Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].

You may return the answer in any order.

A combination is a selection of items without regard to the order of selection.

Input & Output

Example 1 — Basic Case
$ Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
💡 Note: All possible combinations of 2 numbers from range [1,4]: choose 2 from {1,2,3,4}
Example 2 — Single Element
$ Input: n = 1, k = 1
Output: [[1]]
💡 Note: Only one way to choose 1 number from range [1,1]: just [1]
Example 3 — Choose All
$ Input: n = 3, k = 3
Output: [[1,2,3]]
💡 Note: Only one way to choose all 3 numbers from range [1,3]: take everything

Constraints

  • 1 ≤ n ≤ 20
  • 1 ≤ k ≤ n

Visualization

Tap to expand
Combinations Problem INPUT Available Numbers [1, n] 1 2 3 4 n = 4 range size k = 2 selection size Select 2 numbers from {1, 2, 3, 4} without regard to order C(4,2) = 4!/(2!*2!) = 6 Total combinations: 6 ALGORITHM STEPS 1 Backtracking Setup Start with empty combination [] 2 Pick Starting Number Try each number from 1 to n 3 Recurse Forward Add next larger numbers only 4 Collect When k Items Save combination, backtrack Decision Tree (partial) [] [1] [2] [3] [1,2] [1,3] [1,4] ... FINAL RESULT All 6 Valid Combinations [1,2] [1,3] [1,4] [2,3] [2,4] [3,4] Output Array: [[1,2],[1,3],[1,4], [2,3],[2,4],[3,4]] OK - 6 items No duplicates, order ignored [1,2] same as [2,1] Time: O(k * C(n,k)) Key Insight: To avoid duplicates in combinations, always pick numbers in increasing order. When building [1,X], only try X greater than 1. This ensures [1,2] is generated but [2,1] is not - they represent the same combination. The backtracking explores all valid paths while pruning redundant ones automatically. TutorialsPoint - Combinations | Optimal Backtracking Solution
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
32.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen