Development/CodingTest
[์์ด] Visited๋ฅผ ์ด์ฉํ ์์ด
Kirok Kim
2021. 12. 24. 23:47
// arr ๋ฝ๊ธฐ๋ฅผ ํ๋ ค๊ณ ๋ชจ์ ๊ฐ๋ค
// output ์ถ๋ ฅ ๋๋ ๊ฐ
// visited ์ค๋ณต๊ฐ ๋ฐฉ์ง
public class Permutation {
public static void main(String[] args) {
int n = 3;
int[] arr = {1, 2, 3};
int[] output = new int[n];
boolean[] visited = new boolean[n];
perm(arr, output, visited, 0, n, 3);
// Swap ์์ด
// System.out.println();
// permutation(arr, 0, n, 3);
}
// ์ฌ์ฉ ์์: perm(arr, output, visited, 0, n, 3);
static void perm(int[] arr, int[] output, boolean[] visited, int depth, int n, int r) {
if (depth == r) {// 3๊ฐ๊ฐ ๋๋ฉด ์ถ๋ ฅ
print(output, r);
return;
}
for (int i = 0; i < n; i++) {
if (visited[i] != true) {
visited[i] = true;
// ์ซ์ ์ ์ ์๋ฃ(์ฒดํฌ)
output[depth] = arr[i];
// ์ถ๋ ฅํ ์ซ์ ์ ์
// depth๊ฐ ์ถ๋ ฅํ ์ซ์์ ์์น
perm(arr, output, visited, depth + 1, n, r);
// ์ฌ๊ทํจ์ ํธ์ถ
visited[i] = false;
// ์ซ์ ์ ์ ์ทจ์
}
}
}
static void print(int[] arr, int r) {// ์ถ๋ ฅ ๋ฉ์๋
for (int i = 0; i < r; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
}
// Swap ์์ด๊ณผ๋ ๋ค๋ฅธ ์ ์ Swap์ ์ ๋ง ๋ง๊ทธ๋๋ก
// ์์น๋ฅผ ๋ฐ๊พธ๊ณ ์ถ๋ ฅํ๋ ๊ฒ์ด๊ณ Visited๋ ์์๋๋ก ๋ฝ์์ ์ถ๋ ฅ
//๊ฒฐ๊ณผ
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
์ฐธ๊ณ : https://bcp0109.tistory.com/14
์์ด Permutation (Java)
์์ด ์ฐ์ต ๋ฌธ์ ์์ด์ด๋ n ๊ฐ์ ๊ฐ ์ค์์ r ๊ฐ์ ์ซ์๋ฅผ ๋ชจ๋ ์์๋๋ก ๋ฝ๋ ๊ฒฝ์ฐ๋ฅผ ๋งํฉ๋๋ค. ์๋ฅผ ๋ค์ด [1, 2, 3] ์ด๋ผ๋ 3 ๊ฐ์ ๋ฐฐ์ด์์ 2 ๊ฐ์ ์ซ์๋ฅผ ๋ฝ๋ ๊ฒฝ์ฐ๋ [1, 2] [1, 3] [2, 1] [2, 3] [3,
bcp0109.tistory.com
๋ฐ์ํ