Interview questions 08.11. Coins

topic:

coin. Any given number of coin denominations to 25 points, 10 points, 5 points and 1 point, writing code calculating several points n notation. (The results may be very large, you need to be on the results of mold 1000000007)

Example 1:

Input: n-5 =
Output: 2
explanation: There are two ways to make up a total amount:
5 = 5
5 = 1 + 1 + 1 + 1 + 1
Example 2:

Input: n-10 =
Output: 4
Explanation: There are four ways to make up a total amount:
10 = 10
10 = 5 +
10 + 5 = 1 + 1 + 1 + 1 + 1
10 = 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
Description:

note:

You can assume that:

0 <= n (total amount) <= 1000000

 

answer:

Twelve weeks did not how to brush the question, the question must be seen moderate solution of the problem. . Knapsack problem turned out to be a totally shit egg seen Ah, how did Lenovo out of it?

Dimensional dp:

class Solution {
public:
    int waysToChange(int n) {
        vector<vector<int> >dp(4,vector<int>(n+1,0));
        vector<int> value={1,5,10,25};
        dp[0][0]=1;
        dp[1][0]=1;
        dp[2][0]=1;
        DP [ . 3 ] [ 0 ] = . 1 ;
         for ( int i = 0 ; i < . 4 ; i ++) {    // DP [i] [j]: only coins before the i, j reaches the number of currency methods 
            for ( int J = . 1 ; J <= n-; ++ J) {
                 IF (I> 0 ) {
                    dp[i][j]+=dp[i-1][j];
                }
                if(j-value[i]>=0){
                    dp[i][j]+=dp[i][j-value[i]];
                }
                dp[i][j]%=1000000007;
            }
        }
        return dp[3][n];
    }
};

 

 

Since recursion relation dp dp [i] [j] only need to use dp [i-1] [j] and dp [i] [j-coins [i]], which is only used on the line, the current column previous results.

It can be optimized to a one-dimensional array dp:

class Solution {
public:
    int waysToChange(int n) {
        vector<int>dp(n+1,0);
        vector<int> value={1,5,10,25};
        dp[0]=1;
        for(int i=0;i<4;++i){
            for(int j=value[i];j<=n;++j){
                dp[j]=(dp[j]+dp[j-value[i]])%1000000007;
            }
        }
        return dp[n];
    }
};

 

Guess you like

Origin www.cnblogs.com/FdWzy/p/12657484.html