LeetCode 77 - Combinations Solution with Backtracking in Java

Today I solved LeetCode 77 – Combinations using a backtracking approach. The problem asks us to generate all possible combinations of k numbers chosen from 1 to n. Instead of brute force, I used recursion with pruning to reduce unnecessary calls and improve efficiency. Key idea: Build combinations step by step Backtrack when the size reaches k Prune branches where remaining elements are insufficient Here is my Java solution: class Solution { List<List<Integer>> sol = new ArrayList<>(); public List<List<Integer>> combine(int n, int k) { generate(1, n, k, new ArrayList<>()); return sol; } public void generate(int i, int n, int k, List<Integer> sub) { if (k == 0) { sol.add(new ArrayList<>(sub)); return; } for (int j = i; j <= n - k + 1; j++) { sub.add(j); generate(j + 1, n, k - 1, sub); sub.remove(sub.size() - 1); } } } Time Complexity: O(C(n, k)) Space Complexity: O(k) This problem strengthened my understanding of recursion, pruning, and combinatorial generation. Always open to feedback and discussions. #LeetCode #Java #Backtracking #ProblemSolving #CodingJourney

To view or add a comment, sign in

Explore content categories