Print all combinations | Set-2
You're given an array of n elements and a target size r. List every combination of r elements drawn from the array, always moving forward through the array (no revisiting earlier positions) preserving the original index order inside each combination. The input need not be sorted; equal values at different indices are separate choices.
Edge cases: With r = 0, the only valid combination is the empty one. If r > n, no combination is possible. If r = n, the entire array is the sole combination.
Sample Input and Output
Example 1 · Run Sample
arr = [1,2,3]
r = 2 [[1,2],[1,3],[2,3]] Example 2
arr = [1,2]
r = 0 [[]] Example 3
arr = [1]
r = 2 [] - 1 <= arr.length <= 20
- 0 <= r <= 20
Test Cases (3)
Approach: Recursive Pick / Skip
At each index, decide: include this element in the current combination or skip it. Move forward either way. When you've picked r elements, record the combination. Stop early if there aren't enough elements left to fill the remaining slots.
function combinations(arr, r) {
const results = [];
function combine(start, current) {
if (current.length === r) {
results.push([...current]);
return;
}
if (start >= arr.length) return;
if (arr.length - start < r - current.length) return;
current.push(arr[start]);
combine(start + 1, current);
current.pop();
combine(start + 1, current);
}
combine(0, []);
return results;
}Time Complexity: O(C(n, r) × r) — generating all C(n, r) combinations, each of size r
Space Complexity: O(n) for the pick/skip recursion depth (excluding output storage)
Saved in this browser only. Private to you.