æ°å¹´åã«ä¸ã®ãããªè¨äºãæ¸ãã¾ããããã©ã¤ãã©ãªã使ããªãå ´åã®è¨ç®ã«ã¤ãã¦æ¸ãã¦ãªãã£ãã®ã§è¨äºã«ãã¾ãã
çµã¿åããã¨ã¯
ããã¤ãã®è¦ç´ ã®ä¸ãããé çªãåºå¥ããã«ããã¤ãã®è¦ç´ ãé¸ã¶æ¹æ³
å
·ä½çãªããããã®çµã¿åãããå¾ããå ´åãPythonãªãitertools.combinationsã§å¼æ°ã«ä¸ããiterableã®çµã¿åãããè¿ãã¤ãã¬ã¼ã¿ãå¾ããã¾ã
C++ãªãnext_permutationã使ãã¾ããããããããã½ã¼ããã¦ãããªãã¨ãããªãã®ã§æ³¨æãå¿
è¦ã§ã
çµã¿åããã®æ°
\(n\)åã®è¦ç´ ã®ä¸ããã\(k\)åè¦ç´ ãé¸ã¶æ¹æ³ã®åæ°ã¯ä»¥ä¸ã®ããã«éä¹(!)ã使ã£ã¦è¨ç®ã§ãã¾ã
$${\binom nk} = \frac{n!}{k!(n-k)!}=\frac{n(n-1)(n-2)\cdots(n-(k-1))}{k(k-1)(k-2)\cdots 1}$$
æä¸å¦æ ¡ãä½ãã§åå¼·ããæã¯æ¬¡ã®Cã使ã£ã表è¨ã§ç¿ãã¾ãã
$${}_n\mathrm{C}_k$$
Cã使ã£ã表è¨ã¯å½ã«ãã£ã¦(ï¼)æ¸ãæ¹ãéã£ãããããããã§ã
\(C(n, k), {}_n C_k, {}^n C_k, C^k_n, C^n_k,C_{n,k}\)
http://en.wikipedia.org/wiki/Binomial_coefficient
æè¿ã¯ä¸ã§æ¸ãããããªã«ãã³ã使ã£ã表è¨ã§è¦ããããã¨ãå¤ãã§ã
ä¸ã®å¼ã«ä»£å
¥ããã°ãããããã«ä»¥ä¸ã®é¢ä¿ãæãç«ã¤ã®ã§ãè¨ç®ã楽ã«ãªã
$${\binom nk} = {\binom n{n-k}}$$
çµã¿åããã®æ°ã¯\((x + y)^n\)ãå±éããæã®\(x^{n - k}y^k\)ã®ä¿æ°ã«ãªã£ã¦ãã¦ãäºé
ä¿æ°ã¨ãå¼ã°ãã¾ã
åç´ã«è¨ç®ããæ¹æ³
\(\mathrm{O}(k)\)åã®ã«ã¼ãã§ããç¹å®ã®äºé
ä¿æ°ãè¨ç®ã§ãã
å
ã«\(n!\)ãå
¨é¨ä¹ç®ãã¦ããå²ããã¨ããã¨ãè¨èªã«ãã£ã¦ã¯ãªã¼ãã¼ããã¼ãã¦ãã¾ãã®ã§ãé次å²ã£ã¦ãã£ãã»ãããã
$${\binom nk} = \frac{n!}{k!(n-k)!} = \frac{n(n-1)(n-2)\cdots(n-(k-1))}{k(k-1)(k-2)\cdots 1}=\prod_{i=1}^k \frac{n-(i-1)}{i}$$
def comb(n, k): m = 1 if n < 2 * k: k = n - k for i in xrange(1, k + 1): m = m * (n - i + 1) / i return m
åçè¨ç»æ³ã«ããæ¹æ³
次ã®ãããªé¢ä¿å¼ãå©ç¨ãããã¨ã§ããã\(n, k\)ã¾ã§ã®äºé ä¿æ°ãé çªã«æ±ãããã¨ãã§ãã
$$\binom n0 = \binom nn = 1$$
\(1 \le n\)ãã¤\(1\le k \le n - 1\)ã§ãã\(n,k\)ã«ã¤ãã¦
$$\binom nk = \binom{n-1}{k-1} + \binom{n-1}k$$
ãã®é¢ä¿ã¯ãã¹ã«ã«ã®ä¸è§å½¢ã¨ãã¦ç¥ããã¦ãã
ãã®é¢ä¿å¼ã使ãã°ä»¥ä¸ã®ã³ã¼ãã®ããã«ã\(\mathrm{O}(n^2)\)åã®ã«ã¼ãã§\(\binom nn\)ã¾ã§ã®ãã¹ã¦ã®äºé
ä¿æ°ãæ±ãã¦ãããã¨ãã§ãã
ãã ã\(\mathrm{O}(n^2)\)ã®ã¡ã¢ãªã使ãã®ã§æ³¨æãå¿
è¦
def make_comb_dp(n): dp = [[0] * (n + 1) for i in xrange(n + 1)] for i in xrange(n + 1): dp[i][0] = 1 dp[i][i] = 1 for i in xrange(2, n + 1): for j in xrange(1, i): dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] return dp if __name__ == '__main__': for line in make_comb_dp(5): print line
åºå
[1, 0, 0, 0, 0, 0] [1, 1, 0, 0, 0, 0] [1, 2, 1, 0, 0, 0] [1, 3, 3, 1, 0, 0] [1, 4, 6, 4, 1, 0] [1, 5, 10, 10, 5, 1]
åè
ä¸ã®Stack Overflowã®è¨äºã§ã¯å³å¯ã«è¨ç®ããæ¹æ³ä»¥å¤ã«ã
ãã¼ãªã¨å¤æãスターリングの公式ã使ã£ã¦è¿ä¼¼çã«è¨ç®ããæ¹æ³ãæ¸ãã¦ããã¿ããã§ã
äºé ä¿æ°ã®å°ä½ã®è¨ç®ãããã
Dåé¡ã§\(\binom nk \div 2^n\)ã®è¨ç®ã®è©±ãåºã¦ãã
ã¡ãªã¿ã«自分が解いたときã¯Pythonã ã£ãã®ã§ãã¾ããªã¼ãã¼ããã¼ã®å¿é
ããªãã£ãã®ã§ç´ æ´ã«ãã¹ã«ã«ã®ä¸è§å½¢ãè¨ç®ãã¦å¯¾æ°ã¨ãã使ã£ã¦ç¡çããè¨ç®ãã