๋ฐ์ํ
์งํฉ์ ๋ถํ ๊ณผ ์คํธ๋ง ์
- ๊ทธ๋ฃน์ ์์์ ๊ทธ๋ฃน ๋ด ์์์ ์์๋ ์ค์ํ์ง ์์ ์ํฉ
- ์๋ก ๋ค๋ฅธ ์ด ๊ฐ์ ํ์ ๋ค ๊ทธ๋ฃน์ผ๋ก ๋น ๊ทธ๋ฃน ์์ด ๋๋๋ ๋ฐฉ๋ฒ์?
- ์ 2์ข ์คํธ๋ง ์๋ฅผ ๊ตฌํ๋ ํ๋ก๊ทธ๋จ
S = list()
n = 10
k = 4
for i in range(0, 100):
new_list = list()
for j in range(0, 100):
new_list.append(-1)
S.append(new_list)
for i in range(1, n+1):
for j in range(1, i+1):
if (j == 1 or j == i):
S[i][j] = 1
else:
S[i][j] = S[i-1][j-1] + (j*S[i-1][j])
print(S[n][k])
์นดํ๋ ์์ ๋ป๊ณผ ๊ทธ ์์ฉ
- Catalan number
n = int(input())
C = [1]
for round in range(1, n+1):
new_C = 0
i = 0
j = round - 1
while (j >= 0):
new_C += C[i] * C[j]
i += 1
j -= 1
C.append(new_C)
print(C[-1])
→ ์ ๋ค๊ฐํ์ ๋ถํ ๋ฌธ์ ์ ์ฌ์ฉ๋จ
→ ๋๊ฐ์ ์์ง์์ ๋ฌธ์ ์๋ ์ฌ์ฉ๋จ
def catalan_dp(n):
# A dynamic programming based function to find nth
# Catalan number
# Table to store results of subproblems
catalan = [0 for _ in range(n + 1)]
# Initialize the first two values in the table
catalan[0] = 1
catalan[1] = 1
# Fill entries in catalan[] using recursive formula
for i in range(2, n + 1):
for j in range(i):
catalan[i] += catalan[j] * catalan[i - j - 1]
# Return the nth Catalan number
return catalan[n]
# Function to calculate the number of different valid parenthesis sequences
def valid_parentheses_sequences(n):
# The number of valid parenthesis sequences of length 2n is the nth Catalan number
return catalan_dp(n)
# Example usage:
# Let's say we want to find the number of valid parentheses sequences for 3 pairs of parentheses
n_pairs = 3
number_of_sequences = valid_parentheses_sequences(n_pairs)
number_of_sequences
๊ต๋์์ด๊ณผ ๊ฒฝ์ฐ์ ์
def derangement(n):
# ๊ธฐ์ ์ฌ๋ก: D_1 = 0, D_2 = 1
if n == 1:
return 0
if n == 2:
return 1
# ์ฒซ ๋ ๊ต๋์์ด์ ๊ฐ์ ์ ์ฅ
a, b = 0, 1
# 3๋ถํฐ n๊น์ง์ ๊ต๋์์ด์ ๊ณ์ฐ
for i in range(3, n+1):
# ํ์ฌ ๊ต๋์์ด์ ๊ณ์ฐ
cur = (i - 1) * (a + b)
# ๋ค์ ๊ณ์ฐ์ ์ํด ๊ฐ์ ๊ฐฑ์
a, b = b, cur
# n๋ฒ์งธ ๊ต๋์์ด ๊ฐ ๋ฐํ
return b
# ์ฃผ์ด์ง ๋ฌธ์ ์ N ๊ฐ์ 3์
๋๋ค.
n = 3
# ๊ต๋์์ด์ ์๋ฅผ ๊ณ์ฐํฉ๋๋ค.
derangement_n = derangement(n)
derangement_n
๋ฐ์ํ