Skip to content

Instantly share code, notes, and snippets.

@yao2030
Created October 31, 2012 09:15
Show Gist options
  • Save yao2030/3986011 to your computer and use it in GitHub Desktop.
Save yao2030/3986011 to your computer and use it in GitHub Desktop.
Permutations and Permutations of size k, using recursion to implement
public class Permutation
{
public static void perm1(String s) { perm1("", s); }
public static void perm1(String prefix, String s)
{
int N = s.length();
if (N == 0) System.out.println(prefix);
else
{
for(int i = 0; i < N; i++)
perm1(prefix+s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
}
}
public static void perm2(String s, int k)
{
perm2("", s, k);
}
public static void perm2(String prefix, String s, int k)
{
int N = prefix.length();
int M = s.length();
if(N == k) System.out.println(prefix);
else
{
for(int i = 0; i < M; i++)
perm2(prefix+s.charAt(i), s.substring(0, i) + s.substring(i+1, M), 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);
perm2(elements, K);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment