Skip to content

Add all combination #4156

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.thealgorithms.backtracking;

import java.util.ArrayList;
import java.util.List;
public class AllCombination {
public static List<List<Integer>> combinations(int n, int k) {
List<List<Integer>> results = new ArrayList<>();
int[] nums = new int[n];

// Initialize the nums array with values from 1 to n
for (int i = 0; i < n; i++) {
nums[i] = i + 1;
}

backtrack(0, new ArrayList<Integer>(), nums, k, results);

return results;
}

private static void backtrack(int start, List<Integer> curr, int[] nums, int k, List<List<Integer>> results) {
if (curr.size() == k) {
results.add(new ArrayList<Integer>(curr));
return;
}

for (int i = start; i < nums.length; i++) {
curr.add(nums[i]);
backtrack(i + 1, curr, nums, k, results);
curr.remove(curr.size() - 1);
}
}

public static void main(String[] args) {
int n = 5;
int k = 3;
List<List<Integer>> results = combinations(n, k);

System.out.println("All possible combinations of " + k + " numbers out of 1 to " + n + ": ");
for (List<Integer> result : results) {
System.out.println(result.toString());
}
}
}