Lara goods autumn trick: dp cents issue

Problems:
1 min, 2 min, 5 min, 10 min four kinds of coins, an unlimited number of coins of each given cents n (n <= 100000), in combination with a number n may be composed cents?

URL: https://www.nowcoder.com/question/next?pid=18874168&qid=587672&tid=29129649

  Huawei is a plane view from the title similar questions, problems attributable to the simple dp, dp first define [n-], the minimum number of coins stored from the desired 0-n, v [i] storing the denomination of the coin, the initialization dp [0] = 0, the state transition equation derived dp [i] = min {dp [i-1] + 1, dp [iv [j]] +1};

 For the state equation can be understood: cents given n, the number i is set to use the currency, currency denomination is the last k, k assuming full use of credits, then k is the number n / k, then there are formulas:

      dp [i] [n] = dp [i-1] [n-0 * k] + dp [i-1] [n-1 * k] + dp [i-1] [n-2 * k] + ....... + dp [i-1] [nn / k * k]; i.e., all cases comprises: k credits is not used, the use of a credit k, k credits using 2 ....... all with k credits, the state transition equation can be obtained in the form of two-digit groups;

  Dp simplified one dimensional equation: dp [I] dp = [I] + dp [IV [J]] ;

Code:

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
    Scanner input=new Scanner(System.in);
    int n=input.nextInt();
    int coins[]= {1,2,5,10};
    int [] dp=new int[100001];
    dp[0]=1;
    for(int i=0;i<4;i++) {
        for(int j=coins[i];j<=n;j++) {
            dp[j]=(dp[j]+dp[j-coins[i]])%1000000007;
        }
    }
    System.out.println(dp[n]);
    
    }
}

 

Can be understood: the total amount of money for each can be formed, can be as before the beginning of a two-dimensional array derived, the use of a 1 coin, 1 coin 2, 2 1 coins, currency ... 3 3 .... so stop iteration, the money has been increasing j, minus the number of coins are constantly increase, below the formula is the constant iteration, minus

A first coin, the method of subtracting credits 2 ... stop iteration number obtained, the required results can be obtained.

     Time code complexity is only O (n), is much smaller than violent solution method;

dp[j]=(dp[j]+dp[j-coins[i]])%1000000007;


 

 

Guess you like

Origin www.cnblogs.com/lszz/p/11802247.html