728x90
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class main {
static int[] arr = {1, 2, 3, 4};
public static void main(String[] args) {
int n = arr.length;
//순서있는 모든 경우의 수
LinkedList<Integer> perArr = new LinkedList();
int[] perCheck = new int[n];
for (int r = 0; r <= n; r++) {
permutation(n, r, perArr, perCheck);
}
//중복할 수 있는 순서있는 모든 경우의 수
LinkedList<Integer> rePerArr = new LinkedList<Integer>();
for (int r = 0; r <= n; r++) {
rePermutation(n, r, perArr);
}
//조합
for (int r = 0; r <= n; r++) {
int[] comArr = new int[r];
combination(comArr, n, r, 0, 0);
}
// 중복 조합
for (int r = 0; r <= n; r++) {
int[] reComArr = new int[r];
reCombination(reComArr, n, r, 0, 0);
}
}
private static void permutation(int n, int r, LinkedList<Integer> perArr, int[] perCheck) {
if (perArr.size() == r) {
for (int i : perArr) {
System.out.print(i);
}
System.out.println();
return;
}
for (int i = 0; i < n; i++) {
if (perCheck[i] == 0) {
perArr.add(i);
perCheck[i] = 1;
permutation(n, r, perArr, perCheck);
perArr.removeLast();
perCheck[i] = 0;
}
}
}
private static void rePermutation(int n, int r, LinkedList<Integer> rePerArr) {
if (rePerArr.size() == r) {
for (int i : rePerArr) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
for (int i = 0; i < n; i++) {
rePerArr.add(i);
rePermutation(n, r, rePerArr);
rePerArr.removeLast();
}
}
private static void combination(int[] comArr, int n, int r, int index, int target) {
if (r == 0) {
for (int i : comArr) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
if (target == n) return;
comArr[index] = target;
combination(comArr, n, r - 1, index + 1, target + 1);//뽑는경우
combination(comArr, n, r, index, target + 1);//안뽑는경우
}
private static void reCombination(int[] reComArr, int n, int r, int index, int target) {
if (r == 0) {
for (int i : reComArr) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
if (target == n) return;
reComArr[index] = target;
reCombination(reComArr, n, r - 1, index + 1, target);//뽑는경우
reCombination(reComArr, n, r, index, target + 1);//안뽑는경우
}
}
728x90
'Algorithm > Study' 카테고리의 다른 글
6 Recursive Pattern (0) | 2020.09.11 |
---|---|
Swift - Graph Implemetation (0) | 2020.07.20 |
Swift - 순열(Permutation) (0) | 2020.07.11 |
Swift - BFS iteration on Binary Tree (0) | 2020.07.09 |
Swift 배열 처리 (1) | 2020.07.04 |
댓글