-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlec10_61.cpp
49 lines (33 loc) Β· 1.29 KB
/
lec10_61.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
int f(int ind , int T , vector<int> &nums , vector<vector<int>> &dp){
if(ind == 0 ){
if(T % nums[0] == 0) return T / nums[0];
return 1e9;
}
if(dp[ind][T]!=-1) return dp[ind][T];
int notTake = 0 + f(ind - 1 , T , nums,dp);
int take = INT_MAX;
if(nums[ind]<=T) take = 1 + f(ind , T - nums[ind] , nums,dp);
return dp[ind][T] =min(take , notTake);
}
public:
int coinChange(vector<int>& nums, int target) {
int n = nums.size();
vector<vector<int>> dp( n , vector<int> (target+1 , -1));
for(int T = 0 ; T<=target ; T++){
if(T % nums[0] == 0) dp[0][T] = T/nums[0];
else dp[0][T] = 1e9;
}
for(int ind = 1 ; ind<n;ind++){
for(int T = 0 ; T<=target ; T++){
int notTake = 0 + dp[ind - 1][ T];
int take = INT_MAX;
if(nums[ind]<=T) take = 1 + dp[ind ][T - nums[ind]];
dp[ind][T] =min(take , notTake);
}
}
int ans = dp[n-1 ][ target ] ;
if( ans >= 1e9) return -1;
return ans;
}
};