题目^{[1]}
- LeetCode 357. 统计各位数字都不同的数字个数
- LeetCode 357. Count Numbers with Unique Digits
思路 – 组合数学
当 n = 0 时,方案数量为 1 种,即 x = 0
当 n = 1 时,方案数量为 10 种,即 x = \{0, 1, 2, 3, 4, 5, 6, 7, 8, 9\}
当 n >= 2 时,最高位不可有前导零,故有 9 种选择,次高位有 9 种选择,次次高位有 8 种选择,以此类推。假设数的位数为 d,那么该位数情况下,其有方案数为 9 * A^{d-1}_9 。
代码
class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
if (n == 0) return 1;
if (n == 1) return 10;
int ans = 10, cur = 9;
for (int i=1;i<n;++i) {
cur = cur * (10 - i);
ans += cur;
}
return ans;
}
};
参考
[1]. LeetCode 原题. https://leetcode.com/problems/minimum-absolute-sum-difference/
欢迎分享,引用。若转载,请联系我,谢谢配合。 本文地址:https://qoogle.top/xiaoxu-tutorial-leetcode-357-count-numbers-with-unique-digits/
您好~我是腾讯云+社区的运营,关注了您分享的技术文章,觉得内容很棒,我们诚挚邀请您加入腾讯云自媒体分享计划。完整福利和申请地址请见:https://cloud.tencent.com/developer/support-plan
作者申请此计划后将作者的文章进行搬迁同步到社区的专栏下,你只需要简单填写一下表单申请即可,我们会给作者提供包括流量、云服务器等,另外还有些周边礼物。