Advertisement
Guest User

Untitled

a guest
May 27th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class Combinations {
  6. /* Driver */
  7. public static void main(String args[]) {
  8. combs("01234", 2);
  9. System.out.println("done");
  10. }
  11.  
  12. /*
  13. * A method exposed to client to calculate combinations of length k of String in Java.
  14. */
  15. public static void combs(String input, int k) {
  16. combination("", input, k);
  17. }
  18.  
  19. /*
  20. * Private method that keeps an accumulator of the word that it is forming (the root)
  21. * through comb Every recursive call will either terminate if word is empty or k is 0
  22. * or walk through the remaining chars in suffx and attach it to the root
  23. * and recurse on the new root, the new suffx and the new k
  24. */
  25. private static void combination(String comb, String suffx, int k) {
  26. if (k == 0) { // combination reached length k
  27. System.out.println(comb);
  28. } else if (suffx.isEmpty()) { // suffx did not reach length k
  29. // do nothing
  30. } else { // need to recurse still
  31. for (int i = 0; i < suffx.length(); i++) {
  32. combination(comb + suffx.charAt(i), // add the character to the current root
  33. suffx.substring(i + 1, suffx.length()), // only operate on characters past current one on next iteration
  34. k - 1); // we only need k-1 letters now
  35. }
  36. }
  37. }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement