力扣322. 零钱兑换

 

自己的思路记录一下,不难,但是几个判断条件听绕,另外数组的初始值

题目:【https://leetcode.cn/problems/coin-change/description/?envType=study-plan-v2&envId=top-interview-150

 

c++版本

 1 class Solution {
 2 public:
 3     int coinChange(vector<int>& coins, int amount) {
 4         vector<int> cache(amount + 1, INT_MAX);
 5 
 6         cache[0] = 0;
 7         for (int i = 1; i <= amount; ++i) {
 8             for (auto c : coins) {
 9             #if 0
10                 if (i < c)
11                     continue;
12                 else/* if (i == c) {
13                     cache[i] = 1;
14                     break;
15                 } else */{
16                     if (cache[i - c] != INT_MAX && cache[i - c] + 1 < cache[i])
17                         cache[i] = cache[i - c] + 1;
18                 }
19             #else
20                 cache[i] = i >= c && INT_MAX != cache[i - c] && cache[i - c] + 1 < cache[i] ? cache[i - c] + 1 : cache[i];
21             #endif
22             }
23         }
24         return INT_MAX != cache[amount] ? cache[amount] : -1;
25     }
26 };

 

posted @ 2025-04-11 13:07  J&YANG  阅读(4)  评论(0)    收藏  举报