"Algorithms that programmers must master" Dynamic Programming "Part 2"

"Algorithms that programmers must master" Dynamic Programming "Part 2"

In the daily work of programmers, mastering various algorithms is essential. Dynamic programming is a commonly used algorithm and is widely used in solving optimization problems. This article mainly introduces the medium difficulty content of dynamic programming, including two-dimensional DP and digital DP.

2DDP

Two-dimensional dynamic programming (DP) refers to using a two-dimensional array to represent the state, where the first dimension represents which element is selected, and the second dimension represents the currently selected state. This method is particularly useful when solving problems where the state that needs to be transferred is relatively complex.

Example 1: Matrix path counting

Problem description: Given an n × mn \times mn×In the matrix m , how many ways are there in total from the upper left corner to the lower right corner? Each time you can only go right or down.

Idea analysis: define state dpi, j dp_{i,j}dpi,jmeans from ( 1 , 1 ) (1,1)(1,1 ) Go to(i, j) (i,j)(i,j ) , then the state transition equation can be defined as:dpi , j = dpi − 1 , j + dpi , j − 1 dp_{i,j} = dp_{i-1,j} + dp_{i, j-1}dpi,j=dpi1,j+dpi,j1, where dpi − 1 , j dp_{i-1,j}dpi1,jIndicates walking from the above position to (i, j) (i,j)(i,j) d p i , j − 1 dp_{i,j-1} dpi,j1Indicates walking from the left position to (i, j) (i,j)(i,j ) , adding the number of solutions in the two situations can be obtained from(1, 1) (1,1)(1,1 ) Go to(i, j) (i,j)(i,j ) number of options. In particular, wheni = 1 i=1i=1 orj = 1 j=1j=When 1 , there is only one path, sodp 1 , j = dpi , 1 = 1 dp_{1,j}=dp_{i,1}=1dp1,j=dpi,1=1

Finally, return dpn, m dp_{n,m}dpn,mIt is the number of options from the upper left corner to the lower right corner.

int[][] dp = new int[n][m];
for (int i = 0; i < n; i++) {
    
    
    dp[i][0] = 1;
}
for (int i = 0; i < m; i++) {
    
    
    dp[0][i] = 1;
}
for (int i = 1; i < n; i++) {
    
    
    for (int j = 1; j < m; j++) {
    
    
        dp[i][j] = dp[i-1][j] + dp[i][j-1];
    }
}
return dp[n-1][m-1];

Digital DP

Digital DP refers to an algorithm that uses each digit of a number as a state to solve number-related problems. The idea of ​​​​digital DP is to take the numbers apart, process them bit by bit according to the number of digits, solve the number of solutions for each digit, and finally combine them to get the final result.

Example 2: The sum of the numbers is kknumber of k numbers

Problem description: Given two positive integers aaa andbbb , find thata ≤ x ≤ ba \leq x \leq baxb , andxxThe sum of all the numbers in x is equal to kkThe number of natural numbers of k .

Idea analysis: We can use digital DP to solve this problem. Like the previous example, we define the state dpi, j, k dp_{i,j,k}dpi,j,kIndicates that the current processing reaches the iithi digit, the sum of the numbers isjjThe number of options for j . Then the state transition equation can be defined as:dpi , j , k = ∑ d = 0 9 dpi − 1 , j − d , k − 1 dp_{i,j,k} = \sum \limits _{d=0} ^ 9 dp_{i-1,jd,k-1}dpi,j,k=d=09dpi1,jd,k1, where ddd represents the number currently processed, which is theiithi -digit number. Thendpi − 1 , j − d , k − d dp_{i-1,jd,kd}dpi1,jd,kdIt means the previous i − 1 i-1iThe sum of 1 -digit numbers isj − d jdjd , the number of digits isk − 1 k-1kThe number of solutions is 1 , and then put all ddThe situations of d are accumulated together to getdpi, j, k dp_{i,j,k}dpi,j,kvalue. In particular, when i = 0 i=0i=0 andj = k = 0 j=k=0j=k=When 0 , this can be regarded as a legal solution, that is,dp 0, 0, 0 = 1 dp_{0,0,0}=1dp0,0,0=1

Next, we optimize the state of digital DP, because for a number nnn , the sum of its digits is at most9 99 , sodpi, j, k = 0 dp_{i,j,k}=0dpi,j,k=0 whenj > 9 k j>9kj>9 k , that is, the current processing reaches theiithi digit, the sum of numbers is greater than9 k 9kYou can skip it directly at 9k . In addition, in order to facilitate calculation, we can convert the upper limit into a string, such asb = 1234 b=1234b=1234 is converted intos = " 1234 " s="1234"s="1234" , then consider bit by bit, ifsi < d s_i<dsi<d , then the current number cannot beddd , the next bit needs to continue to be considered, ifsi = d s_i=dsi=d , then the current number can be taken asddd , the next bit also needs to be considered, ifsi > d s_i>dsi>d , then the next digit can be filled with any number without further consideration.

When implementing, we need to use a sum sumThe s u m variable is used to record the sum of the various digits of the current number, and the number of solutions in all states is added to obtain the final result.

public int count(int n, int k) {
    
    
    int[][][] dp = new int[11][91][91];
    dp[0][0][0] = 1;
    for (int i = 1; i <= 10; i++) {
    
    
        for (int j = 0; j <= 81; j++) {
    
    
            for (int l = 0; l <= 81; l++) {
    
    
                for (int d = 0; d <= 9; d++) {
    
    
                    if (j >= d && l >= d) {
    
    
                        dp[i][j][l] += dp[i - 1][j - d][l - d];
                    }
                }
            }
        }
    }
    int ans = 0;
    String s = String.valueOf(n);
    int[] num = new int[s.length() + 1];
    for (int i = 0; i < s.length(); i++) {
    
    
        num[i + 1] = s.charAt(i) - '0';
    }
    for (int i = 1; i < num.length; i++) {
    
    
        for (int j = 0; j < num[i]; j++) {
    
    
            if (j <= k - ans - (num.length - i) * 9) {
    
    
                ans += dp[num.length - i][k - ans - j][(num.length - i) * 9 + j];
            }
        }
        if (num[i] > k - ans - (num.length - i) * 9) {
    
    
            break;
        }
        sum += num[i];
    }
    if (sum == k) {
    
    
        ans++;
    }
    return ans;
}

Conclusion

This article mainly introduces the medium difficulty content of dynamic programming, including two-dimensional DP and digital DP, and attaches two example questions as a template reference. Through practical application and practice, I believe readers can have a deeper understanding of the ideas and applications of dynamic programming.

Guess you like

Origin blog.csdn.net/qq_45704048/article/details/132824596