Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.lang.*;
- import java.io.*;
- class Combinations {
- /* Driver */
- public static void main(String args[]) {
- combs("01234", 2);
- System.out.println("done");
- }
- /*
- * A method exposed to client to calculate combinations of length k of String in Java.
- */
- public static void combs(String input, int k) {
- combination("", input, k);
- }
- /*
- * Private method that keeps an accumulator of the word that it is forming (the root)
- * through comb Every recursive call will either terminate if word is empty or k is 0
- * or walk through the remaining chars in suffx and attach it to the root
- * and recurse on the new root, the new suffx and the new k
- */
- private static void combination(String comb, String suffx, int k) {
- if (k == 0) { // combination reached length k
- System.out.println(comb);
- } else if (suffx.isEmpty()) { // suffx did not reach length k
- // do nothing
- } else { // need to recurse still
- for (int i = 0; i < suffx.length(); i++) {
- combination(comb + suffx.charAt(i), // add the character to the current root
- suffx.substring(i + 1, suffx.length()), // only operate on characters past current one on next iteration
- k - 1); // we only need k-1 letters now
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement