Created
October 31, 2012 12:38
-
-
Save yao2030/3986831 to your computer and use it in GitHub Desktop.
Use recursion to implement combination of a set of characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Combination | |
{ | |
public static void combinate(String prefix, String s) | |
{ | |
StdOut.println(prefix); | |
int N = s.length(); | |
if (N == 0) return; | |
for (int i = 0; i < N; i++) | |
combinate(prefix + s.charAt(i), s.substring(i+1, N)); | |
} | |
public static void combinateK(String prefix, String s, int k) | |
{ | |
int N = prefix.length(); | |
int M = s.length(); | |
if (N == k) | |
{ | |
StdOut.println(prefix); | |
return ; | |
} | |
for(int i = 0; i < M; i++) | |
{ | |
combinateK(prefix + s.charAt(i), s.substring(0, i), k); | |
} | |
} | |
public static void main(String[] args) | |
{ | |
String alphabet = "abcdefghijklmnopqrstuvwxyz"; | |
int N = Integer.parseInt(args[0]); | |
int K = Integer.parseInt(args[1]); | |
String elements = alphabet.substring(0, N); | |
combinateK("", elements, K); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment