본문 바로가기

프로그래밍/Algorithm

조합과 순열

1. 조합

  • 집합에서 일부 원소를 취해 부분집합을 만드는 방법
  • 서로 다른 n개의 원소에서 중복을 허용하지 않고 k개를 뽑는 경우의 수
  • 순서가 없음

- 조합의 수(Python)

1
2
3
4
def combination(n, r):
    if n == r or r == 0return 1
    elsereturn combination(n-1, r-1+ combination(n-1, r)
combination(53)
cs

- 조합 출력(Python)

1
2
3
4
5
6
7
8
9
10
11
12
def combination(comArr, n, r, index, target, arr):
    if r==0:print(comArr)
    elif target==n: return
    else:
        comArr[index] = arr[target]
        combination(comArr, n, r-1, index+1, target+1, arr)
        combination(comArr, n, r, index,target +1, arr)
arr = [1,2,3,4]
= len(arr)
= 3
comArr = [0]*r
combination(comArr, n, r, 00, arr)
cs

- 조합 출력(Python - itertools 모듈)

1
2
3
from itertools import combinations
arr = [1,2,3,4]
print(list(combinations(arr, 3)))
cs

- 중복 조합(Python)

1
2
3
4
5
6
7
8
9
10
11
12
def combination(comArr, n, r, index, target, arr):
    if r==0:print(comArr)
    elif target==n: return
    else:
        comArr[index] = arr[target]
        combination(comArr, n, r-1, index+1, target, arr)
        combination(comArr, n, r, index,target +1, arr)
arr = [1,2,3,4]
= len(arr)
= 3
comArr = [0]*r
combination(comArr, n, r, 00, arr)
cs

2. 순열

  • n개의 원소에서 k개의 원소를 골라 순서를 뒤섞는 연산
  • 순서가 있음
  • DFS, visited 배열을 이용함

- 순열 출력(Python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def permutation(permArr, arr, visited, depth, n, r):
    if depth == r:
        print(permArr)
        return
    for i in range(n):
        if visited[i]:
            continue
        visited[i] = True
        permArr[depth] = arr[i]
        permutation(permArr, arr, visited, depth+1, n, r)
        visited[i]= False
        
arr = [1,2,3]
= len(arr)
= 3
permArr = [0]*r
visited = [False]*n
 
permutation(permArr, arr, visited, 0, n, r)
cs

- 순열 출력(Python - itertools 모듈)

1
2
3
from itertools import permutations
arr = [1,2,3,4]
print(list(permutations(arr, 3)))
cs

- 중복 순열(Python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def permutation(permArr, arr, depth, n, r):
    if depth == r:
        print(permArr)
        return
    for i in range(n):
        permArr[depth] = arr[i]
        permutation(permArr, arr, depth+1, n, r)
        
arr = [1,2,3]
= len(arr)
= 3
permArr = [0]*r
 
permutation(permArr, arr, 0, n, r)
cs


참고

https://gorakgarak.tistory.com/523

https://ourcstory.tistory.com/414


'프로그래밍 > Algorithm' 카테고리의 다른 글

너비 우선 탐색(BFS: Breadth First Search)  (0) 2023.03.24
에라토스테네스의 체  (0) 2019.08.27