Java ProgramsRecursionGenerate Combinations

Generate Combinations in Java

intermediate·  Recursion  ·  Recursion

Problem

Generating combinations means listing out every possible group of a fixed size from a larger set, where the order within each group doesn't matter — unlike calculating just the count of how many such groups exist, this actually produces each one.

Given a set of items and a size k, print every combination of k items chosen from that set.

Input
items = {A, B, C}, k = 2
Output
AB AC BC

Java Program

Java
public class GenerateCombinationsRecursion { static char[] items = {'A', 'B', 'C'}; static int k = 2; static void generate(int start, StringBuilder current) { if (current.length() == k) { System.out.println(current); return; } for (int i = start; i < items.length; i++) { current.append(items[i]); generate(i + 1, current); current.deleteCharAt(current.length() - 1); // backtrack before trying the next item } } public static void main(String[] args) { generate(0, new StringBuilder()); } }

Output

AB AC BC

Core Logic

Trying each remaining item in turn, adding it to the partial combination, recursing to fill the rest, and then removing it again before trying the next one, explores every valid group of the right size exactly once.

How It Works
  1. 1generate(start, current) tracks which items are still eligible to be added and what's been chosen so far.
  2. 2The base case if (current.length() == k) fires once the partial combination has reached the target size, printing it.
  3. 3The loop tries every item from start onward, appending one, recursing with i + 1 so the same item can't be picked twice, then removing it again — the classic backtracking pattern.
  4. 4Starting the loop from start rather than 0 every time is what stops BA from being generated alongside AB — once an item is skipped, it's never revisited.
Choosing 2 from {A, B, C}: picking A then trying B and C gives AB and AC; backtracking to just B then trying C gives BC — three combinations in total.
💡

Key Point: Removing the just-added item after recursing — the backtracking step — is what lets the same current buffer be reused for every branch instead of building a fresh copy at each call.

Complexity
Time Complexity: O(C(n, k))Space Complexity: O(k)

Why: The recursion produces exactly C(n, k) complete combinations, and the partial combination being built never holds more than k characters, matching the recursion's depth.

Key Concepts

recursionbacktrackingchoose-and-recurse

Related Programs