Skip to content

Instantly share code, notes, and snippets.

@yao2030
Created October 31, 2012 12:38
Show Gist options
  • Save yao2030/3986831 to your computer and use it in GitHub Desktop.
Save yao2030/3986831 to your computer and use it in GitHub Desktop.
Use recursion to implement combination of a set of 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