algoadvance

Leetcode 77. Combinations

Problem Statement

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.

Example 1:

Input: n = 4, k = 2
Output: [[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]

Example 2:

Input: n = 1, k = 1
Output: [[1]]

Clarifying Questions

  1. Will the input values always be positive integers?
    • Yes, n and k will always be positive integers.
  2. Can k be greater than n?
    • No, k will always be less than or equal to n because you cannot select more elements than are available.
  3. Will the output list need to be sorted or in a specific order?
    • No, the combinations can be returned in any order.

Strategy

This problem is a classic example of generating combinations. We can solve this using backtracking. We will explore all potential combinations by recursively adding elements to a current combination and ensuring that each combination is of length k.

Steps:

  1. Create a helper function backtrack to generate combinations.
  2. Use the function recursively to build each possible combination.
  3. When a valid combination of length k is reached, it is added to the result list.
  4. Continue to explore further combinations by including the next number in the range ([i, n]).
  5. This approach ensures that we explore all combinations.

Code

Here’s the implementation in Java:

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(result, new ArrayList<>(), n, k, 1);
        return result;
    }
    
    private void backtrack(List<List<Integer>> result, List<Integer> current, int n, int k, int start) {
        if (current.size() == k) {
            result.add(new ArrayList<>(current));
            return;
        }
        
        for (int i = start; i <= n; i++) {
            current.add(i);
            backtrack(result, current, n, k, i + 1);
            current.remove(current.size() - 1);
        }
    }
    
    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.combine(4, 2)); // [[2, 4], [3, 4], [2, 3], [1, 2], [1, 3], [1, 4]]
        System.out.println(sol.combine(1, 1)); // [[1]]
    }
}

Time Complexity

Thus, this solution is efficient for moderate values of n and k but may become impractical if n and k are very large.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI