mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
新增C语言实现
This commit is contained in:
@ -389,6 +389,30 @@ function numSquares(n: number): number {
|
||||
};
|
||||
```
|
||||
|
||||
## C
|
||||
|
||||
```c
|
||||
#define min(a, b) ((a) > (b) ? (b) : (a))
|
||||
|
||||
int numSquares(int n) {
|
||||
int* dp = (int*)malloc(sizeof(int) * (n + 1));
|
||||
for (int j = 0; j < n + 1; j++) {
|
||||
dp[j] = INT_MAX;
|
||||
}
|
||||
dp[0] = 0;
|
||||
// 遍历背包
|
||||
for (int i = 0; i <= n; ++i) {
|
||||
// 遍历物品
|
||||
for (int j = 1; j * j <= i; ++j) {
|
||||
dp[i] = min(dp[i - j * j] + 1, dp[i]);
|
||||
}
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
### Rust:
|
||||
|
||||
```rust
|
||||
@ -439,4 +463,3 @@ impl Solution {
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
</a>
|
||||
|
||||
|
@ -352,6 +352,35 @@ func min(a, b int) int {
|
||||
|
||||
```
|
||||
|
||||
## C
|
||||
|
||||
```c
|
||||
#define min(a, b) ((a) > (b) ? (b) : (a))
|
||||
|
||||
int coinChange(int* coins, int coinsSize, int amount) {
|
||||
int* dp = (int*)malloc(sizeof(int) * (amount + 1));
|
||||
for (int j = 0; j < amount + 1; j++) {
|
||||
dp[j] = INT_MAX;
|
||||
}
|
||||
dp[0] = 0;
|
||||
// 遍历背包
|
||||
for(int i = 0; i <= amount; i++){
|
||||
// 遍历物品
|
||||
for(int j = 0; j < coinsSize; j++){
|
||||
if(i - coins[j] >= 0 && dp[i - coins[j]] != INT_MAX){
|
||||
dp[i] = min(dp[i], dp[i - coins[j]] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if(dp[amount] == INT_MAX){
|
||||
return -1;
|
||||
}
|
||||
return dp[amount];
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
### Rust:
|
||||
|
||||
```rust
|
||||
@ -474,4 +503,3 @@ function coinChange(coins: number[], amount: number): number {
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
</a>
|
||||
|
||||
|
Reference in New Issue
Block a user