Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

How to generate all possible k combinations of numbers between 1 and n, in Java?


/*
	This is an implementation that demonstrates
	how to generate all possible k combinations
	out of the range [1, n] 
	

	Time complexity: O(N!/((N-k)!(k-1)!)) 
	Space complexity: O(N!/((N-k)!k!))
*/
import java.util.List;
import java.util.ArrayList;

public class Combinations {

	public static void main(String[] args) {
		int n = 4, k = 2;
		// Below prints: [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
		System.out.println(combine(n, k));
	}

	private static List<List<Integer>> combine(int n, int k) {
		List<List<Integer>> result = new ArrayList<>();
		List<Integer> currentCombo = new ArrayList<>();
		combinationsUtil(currentCombo, 1, result,
				n, k);
		return result;
	}

	private static void combinationsUtil(List<Integer> currentCombo, int first, List<List<Integer>> result, int n,
			int k) {
		if (currentCombo.size() == k) {
			result.add(new ArrayList<>(currentCombo));
			return;
		}

		for (int i = first; i <= n; i++) {
			currentCombo.add(i);
			combinationsUtil(currentCombo, i + 1, result, n, k);
			currentCombo.remove(currentCombo.size() - 1);
		}

	}

}
Comment

PREVIOUS NEXT
Code Example
Java :: zpool 
Java :: Why is it not recommended to use script elements in jsp? 
Java :: bouble to bytes[] java 
Java :: program in java. Get a string from user and also validate it’s length should be at least 1. Pass this string to a method that returns a new string with the first char added at the front and end, so "cat" yields "ccatc". 
Java :: how to change a bukkit chat format 
Java :: make recycler view non scrollable 
Java :: java create list with one element 
Java :: inject in jsp 
Java :: plus one 
Java :: geting max value in priority queue java 
Java :: How to efficiently find a target element in a sorted matrix of distinct ints, in Java? 
Java :: system vs integration testing 
Java :: android java get resource string 
Java :: Java program to find the sum of all even numbers from 1 to 10 
Java :: Input console using java 
Java :: in a junit test how test if empty list is returned 
Java :: immagini java 
Java :: discord jda remove @everyone from channel 
Java :: import for Collectors java 
Java :: java get unix timestamp 
Java :: java real random 
Java :: how to convert an object into string with different fields in java 
Java :: java check if directory exists 
Java :: jackson object to string 
Java :: arrays.aslist.add 
Java :: java jdk java_home home ubuntu openjdk-8-jdk 
Java :: spigot execute command as player 
Java :: java regex ip 
Java :: reverse sentence in java 
Java :: how to check if a string is empty or null in Android Studio 
ADD CONTENT
Topic
Content
Source link
Name
4+2 =