Useful code sample found on the net
The source is here Click here for commentary (https://qiita.com/masakinpo/items/b6ae147d9a61b592240a)
public static void permutation(String q, String ans){
// Base Case
if(q.length() <= 1) {
System.out.println(ans + q);
}
// General Case
else {
for (int i = 0; i < q.length(); i++) {
permutation(q.substring(0, i) + q.substring(i + 1),
ans + q.charAt(i));
}
}
}
public static void combination(String q, String ans, int k){
// Base Case
if(ans.length() == k) {
System.out.println(ans);
}
// General Case
else {
while (q.length() > 0) {
combination(q.substring(1), ans + q.charAt(0), k);
q = q.substring(1);
}
}
}
public static void main(String[] args) {
combination("abcd", "", 2);
}
public static void permutation(String q){
permutation(q, "");
}
private static void permutation(String q, String ans){
//省略
}
Recommended Posts