mirror of
https://github.com/TheAlgorithms/Java.git
synced 2026-03-13 08:40:43 +08:00
### Summary This PR makes small readability and maintainability improvements to the algorithm implementation. ### Changes - Removed a redundant `n < 0` validation check since the method contract already ensures valid `n` - Replaced `current.remove(current.size() - 1)` with `current.removeLast()` to better express backtracking intent ### Rationale - Simplifies input validation without changing behavior - Uses the `Deque` API to make the backtracking step clearer and less error-prone ### Impact - No change in algorithm logic or time/space complexity - Output remains identical Co-authored-by: Swati Vusurumarthi <swativs869@gmail.com>
55 lines
1.9 KiB
Java
55 lines
1.9 KiB
Java
package com.thealgorithms.backtracking;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
/**
|
|
* This class provides methods to find all combinations of integers from 0 to n-1
|
|
* of a specified length k using backtracking.
|
|
*/
|
|
public final class ArrayCombination {
|
|
private ArrayCombination() {
|
|
}
|
|
|
|
/**
|
|
* Generates all possible combinations of length k from the integers 0 to n-1.
|
|
*
|
|
* @param n The total number of elements (0 to n-1).
|
|
* @param k The desired length of each combination.
|
|
* @return A list containing all combinations of length k.
|
|
* @throws IllegalArgumentException if n or k are negative, or if k is greater than n.
|
|
*/
|
|
public static List<List<Integer>> combination(int n, int k) {
|
|
if (k < 0 || k > n) {
|
|
throw new IllegalArgumentException("Invalid input: 0 ≤ k ≤ n is required.");
|
|
}
|
|
|
|
List<List<Integer>> combinations = new ArrayList<>();
|
|
combine(combinations, new ArrayList<>(), 0, n, k);
|
|
return combinations;
|
|
}
|
|
|
|
/**
|
|
* A helper method that uses backtracking to find combinations.
|
|
*
|
|
* @param combinations The list to store all valid combinations found.
|
|
* @param current The current combination being built.
|
|
* @param start The starting index for the current recursion.
|
|
* @param n The total number of elements (0 to n-1).
|
|
* @param k The desired length of each combination.
|
|
*/
|
|
private static void combine(List<List<Integer>> combinations, List<Integer> current, int start, int n, int k) {
|
|
// Base case: combination found
|
|
if (current.size() == k) {
|
|
combinations.add(new ArrayList<>(current));
|
|
return;
|
|
}
|
|
|
|
for (int i = start; i < n; i++) {
|
|
current.add(i);
|
|
combine(combinations, current, i + 1, n, k);
|
|
current.removeLast(); // Backtrack
|
|
}
|
|
}
|
|
}
|