File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change
1
+ #
2
+ # @lc app=leetcode id=322 lang=python3
3
+ #
4
+ # [322] Coin Change
5
+ #
6
+
7
+ # @lc code=start
8
+ INF = 10 ** 7
9
+ class Solution :
10
+ def coinChange (self , C : List [int ], S : int ) -> int :
11
+ noCoins = len (C )
12
+ dp = [[INF for _ in range (noCoins + 1 )] for _ in range (S + 1 )]
13
+ # dp[i][j] is min coins needed to make sum "i" when first "j" coins are available
14
+ dp [0 ][0 ] = 0 # no coin needed to make 0
15
+ for i in range (0 , S + 1 ):
16
+ for j in range (1 , noCoins + 1 ):
17
+ curCoin = C [j - 1 ] # 0-based indexing
18
+
19
+ # Case A: I don't take jth coin
20
+ dp [i ][j ] = dp [i ][j - 1 ]
21
+
22
+ # Case B: I take jth coin
23
+ if curCoin <= i :
24
+ dp [i ][j ] = min (dp [i ][j ], 1 + dp [i - curCoin ][j ])
25
+ return dp [S ][noCoins ] if dp [S ][noCoins ] != INF else - 1
26
+
27
+ # @lc code=end
28
+
You can’t perform that action at this time.
0 commit comments