Skip to content

Commit

Permalink
feat: problem azl397985856#322 add C++ implementation (azl397985856#177)
Browse files Browse the repository at this point in the history
  • Loading branch information
raof01 authored and azl397985856 committed Sep 17, 2019
1 parent a670991 commit b2af572
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion problems/322.coin-change.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ eg: 对于 [1,2,5] 组成 11 块
- 对于每一个 dp[i] 我们都选择遍历一遍 coin, 不断更新 dp[i]

## 代码

* 语言支持:JS,C++

JavaScript Code:
```js
/*
* @lc app=leetcode id=322 lang=javascript
Expand Down Expand Up @@ -134,7 +138,25 @@ var coinChange = function(coins, amount) {

};
```

C++ Code:
> C++中采用INT_MAX,因此判断时需要加上`dp[a - coin] < INT_MAX`以防止溢出
```C++
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
auto dp = vector<int>(amount + 1, INT_MAX);
dp[0] = 0;
for (auto a = 1; a <= amount; ++a) {
for (const auto & coin : coins) {
if (a >= coin && dp[a - coin] < INT_MAX) {
dp[a] = min(dp[a], dp[a-coin] + 1);
}
}
}
return dp[amount] == INT_MAX ? -1 : dp[amount];
}
};
```
## 扩展
这是一道很简单描述的题目, 因此很多时候会被用到大公司的电面中。
Expand Down

0 comments on commit b2af572

Please sign in to comment.