[알고리즘] 수열의 순열과 조합
순열( )과 조합( )
특정 수열에 대해 순열과 조합을 구하는 방법을 알아보자.
먼저 순열은 Permutation의 앞 글자를 따서
예를 들어, { 1, 2, 3 }이란 수열이 있고,
{1, 2}, {2, 1}, {1, 3}, {3, 1}, {2, 3}, {3, 2} <-------- 총 6개
순열은 정렬이 의미가 있기 때문에 {1, 2}와 {2, 1}은 구분된다.
다음으로 조합은 Combination의 앞 글자를 따서
{ 1, 2, 3 } 수열에서
{1, 2}, {1, 3}, {2, 3} <-------- 총 3개
조합은 정렬이 의미가 없기 때문에 {1, 2}와 {2, 1}은 같은 걸로 취급된다.
코드
먼저 조합을 구하는 코드를 살펴보자.
public class Combination { public static void main(String[] args) { int[] arr = { 1, 3, 5, 7, 9 }; int n = arr.length, r = 3; int[] combArr = new int[n]; doCombination(combArr, n, r, 0, 0, arr); } private void doCombination(int[] combArr, int n, int r, int index, int target, int[] arr) { if (r == 0) { for (int i = 0; i < index; i++) System.out.print(arr[combArr[i]] + " "); System.out.println(); } else if (target == n) return; else { combArr[index] = target; doCombination(combArr, n, r - 1, index + 1, target + 1, arr); // (i) doCombination(combArr, n, r, index, target + 1, arr); // (ii) } } }
참고자료
[1] https://onsil-thegreenhouse.github.io/programming/algorithm/2018/04/05/permutation_combination/
'Algorithm > Theory' 카테고리의 다른 글
[알고리즘] 최단 경로 - Dijkstra 알고리즘 (0) | 2020.10.25 |
---|---|
[알고리즘] 최단 경로 - Floyd-Warshall 알고리즘 (0) | 2020.10.16 |
[알고리즘] LCS(Longest Common Subsequence) (0) | 2020.09.13 |
[알고리즘] 최소 공통 조상 - LCA(Lowest Common Acestor) (0) | 2020.09.10 |
[알고리즘] 최소비용 신장트리(MST) - Prim 알고리즘 (0) | 2020.09.07 |
댓글
이 글 공유하기
다른 글
-
[알고리즘] 최단 경로 - Dijkstra 알고리즘
[알고리즘] 최단 경로 - Dijkstra 알고리즘
2020.10.25 -
[알고리즘] 최단 경로 - Floyd-Warshall 알고리즘
[알고리즘] 최단 경로 - Floyd-Warshall 알고리즘
2020.10.16 -
[알고리즘] LCS(Longest Common Subsequence)
[알고리즘] LCS(Longest Common Subsequence)
2020.09.13 -
[알고리즘] 최소 공통 조상 - LCA(Lowest Common Acestor)
[알고리즘] 최소 공통 조상 - LCA(Lowest Common Acestor)
2020.09.10
댓글을 사용할 수 없습니다.