뱀귤님 블로그 예제가 이해하기쉽게 잘 작성되어있어서 스터디 후 원하던 방향으로 응용.
순열 : https://bcp0109.tistory.com/14
조합(중복이 싫은경우) : https://bcp0109.tistory.com/15
배열 : 1, 2, 3, 4
기대값 :
[1]
[2]
[3]
[4]
[1, 2]
[1, 3]
[1, 4]
[2, 1]
[2, 3]
[2, 4]
[3, 1]
[3, 2]
[3, 4]
[4, 1]
[4, 2]
[4, 3]
[1, 2, 3]
[1, 2, 4]
[1, 3, 2]
[1, 3, 4]
[1, 4, 2]
[1, 4, 3]
[2, 1, 3]
[2, 1, 4]
[2, 3, 1]
[2, 3, 4]
[2, 4, 1]
[2, 4, 3]
[3, 1, 2]
[3, 1, 4]
[3, 2, 1]
[3, 2, 4]
[3, 4, 1]
[3, 4, 2]
[4, 1, 2]
[4, 1, 3]
[4, 2, 1]
[4, 2, 3]
[4, 3, 1]
[4, 3, 2]
[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 3, 2, 4]
[1, 3, 4, 2]
[1, 4, 2, 3]
[1, 4, 3, 2]
[2, 1, 3, 4]
[2, 1, 4, 3]
[2, 3, 1, 4]
[2, 3, 4, 1]
[2, 4, 1, 3]
[2, 4, 3, 1]
[3, 1, 2, 4]
[3, 1, 4, 2]
[3, 2, 1, 4]
[3, 2, 4, 1]
[3, 4, 1, 2]
[3, 4, 2, 1]
[4, 1, 2, 3]
[4, 1, 3, 2]
[4, 2, 1, 3]
[4, 2, 3, 1]
[4, 3, 1, 2]
[4, 3, 2, 1]
import java.util.Arrays;
public class Permutation {
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3, 4};
int length = array.length;
int[] output = new int[length];
boolean[] isVisit = new boolean[length];
for(int cnt=1; cnt<=length; cnt++) {
permutation(array, output, isVisit, 0, length, cnt);
}
System.out.println();
}
public static void permutation(int[] array, int[] output, boolean[] isVisit, int depth, int length, int count) {
if(count==0) {
System.out.println(Arrays.toString(Arrays.stream(output).filter(i -> i!=0).toArray()));
return;
}
for(int i=0; i<length; i++) {
if(isVisit[i]!=true) {
isVisit[i] = true;
output[depth] = array[i];
permutation(array, output, isVisit, depth+1, length, count-1);
isVisit[i] = false;
}
}
}
/*
위와 동일.
for(int cnt=1; cnt<=4; cnt++) {
perm_recur_count(new int[] {1, 2, 3, 4}, new boolean[4], new int[4], new boolean[4], 0, cnt);
}
*/
public static void perm_recur_count(int[] input, boolean[] isOutput, int[] output, boolean[] isDepth, int depth, int count) {
if(count==0) {
for(int i=0, max=output.length; i<max; i++) {
if(isOutput[i]) {
System.out.print(output[i] + " ");
}
}
System.out.println();
return;
}
for(int i=0, max=input.length; i<max; i++) {
if(isDepth[i]!=true) {
isDepth[i] = true;
output[depth] = input[i];
isOutput[depth] = true;
perm_recur_count(input, isOutput, output, isDepth, depth+1, count-1);
isDepth[i] = false;
isOutput[depth] = false;
}
}
}
}
'Other > 알고리즘' 카테고리의 다른 글
소수 구하기(PrimeNumber) (0) | 2020.05.09 |
---|