Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

k combinations for range 1 through n


/*
	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 :: java product 1 to n 
Java :: Example on: Getting the substring after the first occurrence of a separator in Java 
Java :: vector inline java 
Java :: convert string to char array in java 
Java :: bukkit chat format 
Java :: jbutton actionlistener 
Java :: turn off focus border java 
Java :: Bukkit debug message 
Java :: android how to start a new activity on button click 
Java :: dialog box in java swing 
Java :: .tar to .ova 
Java :: how to create javafx project in eclipse 
Java :: java stream to list 
Java :: java printf leading zeros 
Java :: list java processes 
Java :: set drawableleft programmatically android 
Java :: show confirmation dialog java android 
Java :: closest fraction to pi 
Java :: Traversing a double dimensional array 
Java :: circular list java 
Java :: why java is popular 
Java :: Which of the following is the only Java package that is imported by default? 
Java :: swing enter key 
Java :: react native android gif 
Java :: how to get float value in json java 
Java :: file to image javafx 
Java :: abstract vs final 
Java :: change java version maven 
Java :: how to read a text file in java 
Java :: create file from byte array java 
ADD CONTENT
Topic
Content
Source link
Name
8+1 =