518.Change exchange||
Analysis: Still don’t quite understand
Idea:
- 1. dp storage, when the amount is j, there are dp[j] combination methods
- 2.dp[j]+=dp[j-coins[i]] As long as the amount j can be reached by adding conins[i]
- 3. All initialized to 0
- 4. Traversal order: traverse coins in the outer layer, traverse amounts in the inner layer
class Solution {
public:
int change(int amount, vector<int>& coins) {
int n=coins.size();
vector<int>dp(amount+1,0);
dp[0]=1;
for(int i=0;i<n;i++){
for(int j=coins[i];j<=amount;j++){
dp[j]+=dp[j-coins[i]];
}
}
return dp[amount];
}
};
377. Combining Sums IV
Idea:
- 1.dp storage: the sum is j, and there are dp[j] kinds of combinations
- 2.dp+=dp[j-nums[i]]
- 3.dp[0]=1
- 4. Traversal order: The outer layer traverses the backpack, and the inner layer traverses the elements (arrangement)
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
int n=nums.size();
vector<int>dp(target+1,0);
dp[0]=1;
for(int i=0;i<=target;i++){
for(int j=0;j<n;j++){
if(i>=nums[j] && dp[i]<=INT_MAX-dp[i-nums[j]]){
dp[i]+=dp[i-nums[j]];
}
}
}
return dp[target];
}
};
70. Advanced stair climbing
Idea:
- 1.dp storage: i-th staircase, there are dp[i] methods
- 2.dp[i]+=dp[i-nums[j]]
- 3. Initialization: dp[0]=1
- 4. Traversal order: 1 2 and 2 1 are different, so they are arranged
class Solution {
public:
int climbStairs(int n) {
vector<int>dp(n+1,0);
dp[0]=1;
int m=1;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(i>=j){
dp[i]+=dp[i-j];
}
}
}
return dp[n];
}
};
322. Change Exchange
Idea:
- 1.dp storage: when the amount is j, the minimum number of coins used is dp[j]
- 2.dp[j]=min(dp[j],dp[j-coins[i]]+1)
- 3. Initialization: dp[0]=1
- 4. Traversal order: combination, the outer layer traverses the coins, the inner layer traverses the amount
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int>dp(amount+1,INT_MAX);
dp[0]=0;
for(int i=0;i<coins.size();i++){
for(int j=coins[i];j<=amount;j++){
if(dp[j-coins[i]]!=INT_MAX)
dp[j]=min(dp[j-coins[i]]+1,dp[j]);
}
}
if(dp[amount]==INT_MAX) return -1;
return dp[amount];
}
};