[Algorithm] Dynamic programming basic question bank 1-7 python implementation

Ugly number

Ugly numbers are numbers with only prime factors of 2, 3, or 5. The number sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15,… shows the first 11 ugly numbers. By convention, it includes 1. Given a number n, please find the nth ugly number.

First, how to judge whether a number is an ugly number? Divide this number by the largest possible powers of 2, 3, and 5. If you end up with 1, it is an ugly number.

Because the prime factors of ugly numbers are only 2, 3, and 5, the numbers in the ugly number sequence will be divided into three groups:

  1. 1x2, 2x2, 3x2, 4x2, 5x2, …
  2. 1x3, 2x3, 3x3, 4x3, 5x3, ...
  3. 1x5, 2x5, 3x5, 4x5, 5x5, ...

Each sub-sequence is the ugly number itself multiplied by 2, 3, and 5. So we can get all the ugly numbers by merging three sub-series like merge sort.

  1. Declare the ugly number sequence: ugly[n]

  2. Initialize the first ugly number: ugly[0] = 1

  3. Initialize the indexes of the three sub-arrays, pointing to the first element of the sub-array: i2 = i3 = i5 = 0

  4. Initialize the possible values ​​of the three next ugly numbers:

    next_multiple_of_2 = ugly[i2] * 2;

    next_multiple_of_3 = ugly[i3] * 3;

    next_multiple_of_5 = ugly[i5] * 5;

  5. Fill the dp array

import time


def getNthUglyNo(n):
    ugly = [0] * n
    ugly[0] = 1
    i2 = i3 = i5 = 0

    next_multiple_of_2 = 2
    next_multiple_of_3 = 3
    next_multiple_of_5 = 5

    for i in range(1, n):
        ugly[i] = min(next_multiple_of_2,
                      next_multiple_of_3,
                      next_multiple_of_5)

        if ugly[i] == next_multiple_of_2:
            i2 += 1
            next_multiple_of_2 = ugly[i2] * 2

        if ugly[i] == next_multiple_of_3:
            i3 += 1
            next_multiple_of_3 = ugly[i3] * 3

        if ugly[i] == next_multiple_of_5:
            i5 += 1
            next_multiple_of_5 = ugly[i5] * 5

    return ugly[-1]


# Driver code
time_start = time.time()
no = getNthUglyNo(150)
time_end = time.time()
print('150th ugly no is', no)
print('cost ', (time_end - time_start) * 1000, 'ms')

Since the time complexity is O(n), there is no way to print it out when used.

Fibonacci sequence

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …
Describe in mathematical terms:
F n = F n-1 + F n-2
Seed number: F 0 = 0, F 1 = 1
Given a number n, find the nth Fibonacci number

Similar to the previous question, build a dp array from bottom to top

def getNthFiboNo(n):
    Fibo = [0] * (n)
    Fibo[0] = 0
    Fibo[1] = 1
    if n <= 1:
        return Fibo[n]
    for i in range(2, n):
        Fibo[i] = Fibo[i - 2] + Fibo[i - 1]
    return Fibo[-1]


no = getNthFiboNo(9)
print('9th fibonacci no is', no)

# 9th fibonacci no is 21

Cattleya Number

The introduction of Cattleya numbers is very clear in this article , and it is similar to the above two questions to construct a dp array.

def getNthCatalanNo(n):
    if(n == 0 or n == 1):
        return 1
    catalan = [0] * n
    catalan[0] = 1
    catalan[1] = 1
    for i in range(2, n):
        for j in range(i):
            catalan[i] += catalan[j] * catalan[i - j - 1]
    return catalan[-1]


no = getNthCatalanNo(10)
print('10th catlan no is', no)

Bell number

Application: Given a set of n elements, how many sub-sets does the set have?
The solution of this problem is Bell Number, and the recurrence equation of this number is:
∑ k = 0 n S (n, k) \sum_{k=0}^{n}S(n, k)k=0nS(n,k)
S ( n + 1 , k ) = k ∗ S ( n , k ) + S ( n , k − 1 ) S(n+1, k) = k*S(n, k) + S(n, k-1) S(n+1,k)=kS(n,k)+S(n,k1 )
Another method is to use Bell's triangle to construct a two-digit dp array to solve

1
1 2
2 3 5
5 7 10 15
15 20 27 37 52
def bellNumber(n):

    bell = [[0 for i in range(n+1)] for j in range(n+1)]
    bell[0][0] = 1
    for i in range(1, n+1):
        bell[i][0] = bell[i-1][i-1]

        for j in range(1, i+1):
            bell[i][j] = bell[i-1][j-1] + bell[i][j-1]

    return bell[n][0]


# Driver program
for n in range(6):
    print('Bell Number', n, 'is', bellNumber(n))

Binomial coefficient

The binomial coefficient C(n, k) can be defined as the coefficient of x k in the expansion of (1 + x) n . Please implement this function.

First, divide the substructure:
C (n, k) = C (n − 1, k − 1) + C (n − 1, k) C(n, k) = C(n-1, k-1) + C(n-1, k)C(n,k)=C(n1,k1)+C(n1,k)
C ( n , 0 ) = C ( n , n ) = 1 C(n, 0) = C(n, n) = 1 C(n,0)=C(n,n)=1
Therefore, repeat the substructure to construct the dp array:

def binomalCoef(n, k):
    C = [[0 for i in range(k+1)] for i in range(n+1)]

    for i in range(n+1):
        for j in range(min(i, k)+1):
            if j == 0 or j == i:
                C[i][j] = 1
            else:
                C[i][j] = C[i-1][j-1] + C[i-1][j]
    return C[n][k]


n = 5
k = 2
print('binomial coefficient (5, 2) is', binomalCoef(n, k))

Permutation factor

Permutation refers to the process of arranging all members of a given set into a sequence. The number of permutations on a set of n elements is the factorial of n.
The permutation coefficient represented by P(n, k) is used to represent the number of ways to obtain an ordered subset of k elements from a set of n elements.
Implement the method.

Using mathematical knowledge, the solution of this method is:
P (n, k) = n (n − 1) (n − 2)... (N − k + 1) (k <= n) P(n, k ) = n(n-1)(n-2)...(n-k+1) (k <= n)P(n,k)=n(n1)(n2)...(nk+1)(k<=n)

P ( n , k ) = n ! ( n − k ) ! P(n, k) = \frac{n!}{(n-k)!} P(n,k)=(nk)!n!

therefore,

def permutationCoeff(n, k): 
  
    P = [[0 for i in range(k + 1)]  
            for j in range(n + 1)] 
  
    # 计算排列系数
    # 由底至上 
    for i in range(n + 1): 
        for j in range(min(i, k) + 1): 
  
            # 初始值
            if (j == 0): 
                P[i][j] = 1
   
            else: 
                P[i][j] = P[i - 1][j] + ( 
                           j * P[i - 1][j - 1]) 
  
            # 如果j小于k,则返回0
            if (j < k): 
                P[i][j + 1] = 0
    return P[n][k]


n = 10
k = 2
print("Value fo P(", n, ", ", k, ") is ", 
       permutationCoeff(n, k), sep = "")

Guess you like

Origin blog.csdn.net/qq_35714301/article/details/113760087