当前位置:网站首页>leetcode2310. 个位数字为 K 的整数之和(中等,周赛)
leetcode2310. 个位数字为 K 的整数之和(中等,周赛)
2022-07-02 01:51:00 【重you小垃】



方法一:完全背包
在包含结尾是k的数组中,每个元素可选多次,和为num的最少个数
class Solution {
public:
int minimumNumbers(int num, int k) {
if (k % 2 == 0 && (num & 1)) return -1;
if (num == 0) return 0;
vector<int> coins;
for (int i = 1; i <= num; ++i) {
if (i % 10 == k) coins.push_back(i);
}
int n = coins.size();
vector<int> dp(num + 1, num + 1);
dp[0] = 0;
for (int i = 0; i < n; ++i) {
for (int j = coins[i]; j <= num; ++j) {
dp[j] = min(dp[j - coins[i]] + 1, dp[j]);
}
}
return dp[num] == num + 1 ? -1 : dp[num];
}
};
方法二:考虑个位数->数学问题
具体思路:i最少个数为1,最多为num,num只有3000,因此可以试着枚举
假设每个元素
x= 10m+k
即找到最小的i使得num=10m’+ik成立,即:遍历i,使得 (num-i k)%10==0 ,找到即return i
class Solution {
public:
int minimumNumbers(int num, int k) {
if (!num) return 0;
for (int i = 1; i <= num && num - i * k >= 0; ++i) {
if ((num - i * k) % 10 == 0) return i;
}
return -1;
}
};
边栏推荐
- 734. Energy stone (greed, backpack)
- 1217 supermarket coin processor
- [Obsidian] wechat is sent to Obsidian using remotely save S3 compatibility
- Openssl3.0 learning XXI provider encoder
- 自动浏览拼多多商品
- 开发工具创新升级,鲲鹏推进计算产业“竹林”式生长
- The role of artificial intelligence in network security
- This is the form of the K-line diagram (pithy formula)
- 2022 Q2 - 提升技能的技巧总结
- Six lessons to be learned for the successful implementation of edge coding
猜你喜欢

SAP ui5 beginner tutorial 20 - explanation of expression binding usage of SAP ui5
![[Floyd] post disaster reconstruction](/img/7a/f72c7781ef148212c870a56fb9a607.jpg)
[Floyd] post disaster reconstruction

【视频】马尔可夫链原理可视化解释与R语言区制转换MRS实例|数据分享

matlab 使用 resample 完成重采样
![[Maya] the error of importing Maya into Metahuman](/img/46/46bd1c2d507c9e48ef8c066c54231d.jpg)
[Maya] the error of importing Maya into Metahuman

人工智能在网络安全中的作用

医药管理系统(大一下C语言课设)

Convolutional neural network (including code and corresponding diagram)

【LeetCode 43】236. The nearest common ancestor of binary tree

479. Additive binary tree (interval DP on the tree)
随机推荐
What are the skills of spot gold analysis?
Experimental reproduction of variable image compression with a scale hyperprior
KS006基于SSM实现学生成绩管理系统
Basic concepts of machine learning
matlab 使用 resample 完成重采样
Medical management system (C language course for freshmen)
企业应该选择无服务器计算吗?
Openssl3.0 learning XXI provider encoder
Failed to transform file 'xxx' to match attributes
This is the report that leaders like! Learn dynamic visual charts, promotion and salary increase are indispensable
matlab 使用 audioread 、 sound 读取和播放 wav 文件
Laravel artisan 常用命令
uTools
[Video] Markov chain Monte Carlo method MCMC principle and R language implementation | data sharing
It's already 30. Can you learn programming from scratch?
PR second training
Regular expression learning notes
Altium designer measure distance (ctrl+m)
Construction and maintenance of business websites [14]
Laravel artisan common commands