Created
October 31, 2012 09:15
-
-
Save yao2030/3986011 to your computer and use it in GitHub Desktop.
Permutations and Permutations of size k, using recursion to implement
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 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