算法设计作业10

本文介绍了一种解决LeetCode上357题Count Numbers with Unique Digits的方法,该题要求计算在0≤x<10^n范围内具有唯一数字的整数数量。通过使用排列组合原理,文章提供了一个简洁高效的C++实现方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第十周作业:

357. Count Numbers with Unique Digits


解题思路:



357. Count Numbers with Unique Digits

Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.

Example:
Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding [11,22,33,44,55,66,77,88,99])



思路:这道题是典型的排列组合问题,有0-9, 10个数字,从左到右第一位不能是0,只能在0-9中选一个,第二位则可以在剩下9个中选,然后剩下8个。。。并且要数位少一位的情况,比如5位数包括了4位数,3位数以及2位数和1位数的结果。

代码如下:
class Solution {
public:
	int countNumbersWithUniqueDigits(int n) {
		int result = 1, num = 9;
		if (n) {
			result = 10;
			for (int i = 2; i <= n; i++) {
				num *= (9 - i + 2);
				result += num;
			}
		}
		return result;
	}
};


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值