topic:
In just saw the title, it is natural to think of using dfs, exhaust all possibilities, although it is possible to know a timeout, but still ... really do overtime
Then read the solution to a problem, dynamic programming (bottom-up) particularly clear
analysis:
Definition of F (i) represents a minimum number of required composition i dollars
So there,
F(0)=0
The ultimate goal is to obtain F (amount)
Transition between different states is a formula F. (I) = min (F. (Cj-i)) + . 1 , 0 = <j <coins.size () a j-th where Cj representative of the value of the denomination of the coin, if there i -Cj <0, simply ignored
When seeking F. (I), only you need to know each F (i-Cj), and F (i-Cj) until i is known, and it can be calculated
Code:
class Solution { public: int coinChange(vector<int>& coins, int amount) { vector<int> F(amount+1, amount); F[0] = 0; for(int i=1; i<=amount; i++){ int cur=INT_MAX; for(int j=0; j<coins.size(); j++){ if(i-coins[j]<0) continue; else if(F[i-coins[j]]>=0 && cur > F[i-coins[j]] ) cur = F[i-coins[j]]+1; } F[i] = cur == INT_MAX?-1:cur; } return F[amount]; } };