当前位置:网站首页>LeetCode刷题——统计各位数字都不同的数字个数#357#Medium
LeetCode刷题——统计各位数字都不同的数字个数#357#Medium
2022-07-02 12:04:00 【喷火龙与水箭龟】
统计各位数字都不同的数字个数的思路探讨与源码
统计各位数字都不同的数字个数的题目如下图,该题属于数学类和回溯类型的题目,主要考察对于回溯方法的使用和题目数学思路的理解。本文的题目作者想到2种方法,分别是排列组合方法和递推方法,其中排列组合方法使用Java进行编写,而递推方法使用Python进行编写,当然这可能不是最优的解法,还希望各位大佬给出更快的算法。
本人认为该题目可以使用排列组合方法的思路进行解决,首先判断数字是否为0或者1,如果是0就返回1;如果是1就返回10,然后开始初始化结果变量和下标变量。开始遍历循环,用当前下标结果记录临时排列结果,然后再加到结果变量上,直到遍历结束后返回最终的结果。那么按照这个思路我们的Java代码如下:
#喷火龙与水箭龟
class Solution {
public int countNumbersWithUniqueDigits(int n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return 10;
}
int resFinal = 10;
int ind = 9;
for (int jr = 0; jr < n - 1; jr++) {
ind = ind * (9 - jr);
resFinal = resFinal + ind;
}
return resFinal;
}
}
显然,我们看到排列行组合方法的效果还可以,同时还可以使用递推的方法解决。首先初始化一个列表,并赋值9个0为初始化结果。让第一个列表元素是1,第二个列表元素是10,然后开始从第二个元素开始遍历循环,通过推演总结后使用数学递推公式进行计算,得到遍历结果后返回最后一个列表的元素即可。所以按照这个思路就可以解决,下面是Python代码:
#喷火龙与水箭龟
class Solution:
def countNumbersWithUniqueDigits(self, n: int) -> int:
vc = []
for ij in range(9):
vc.append(0)
vc[0] = 1
vc[1] = 10
for jr in range(2,9):
vc[jr] = vc[jr-1] + (vc[jr-1]-vc[jr-2])*(10-(jr-1))
return vc[n]
从结果来说Java版本的排列组合方法的效率不错,而Python版本的递推方法的速度也还可以,但应该是有更多的方法可以进一步提速的,希望朋友们能够多多指教,非常感谢。
边栏推荐
- Huffman tree: (1) input each character and its weight (2) construct Huffman tree (3) carry out Huffman coding (4) find hc[i], and get the Huffman coding of each character
- Tidb data migration scenario overview
- There are 7 seats with great variety, Wuling Jiachen has outstanding product power, large humanized space, and the key price is really fragrant
- 13_Redis_事务
- 17_ Redis_ Redis publish subscription
- Kibana basic operation
- 2021-2022学年编译原理考试重点[华侨大学]
- TiDB数据迁移场景综述
- 10_Redis_geospatial_命令
- I made an istio workshop. This is the first introduction
猜你喜欢
Mavn 搭建 Nexus 私服
kibana 基础操作
Tidb data migration tool overview
17_ Redis_ Redis publish subscription
20_ Redis_ Sentinel mode
I made an istio workshop. This is the first introduction
18_ Redis_ Redis master-slave replication & cluster building
解决el-radio-group 回显后不能编辑问题
损失函数与正负样本分配:YOLO系列
How to find a sense of career direction
随机推荐
6.12 企业内部upp平台(Unified Process Platform)的关键一刻
GeoServer offline map service construction and layer Publishing
如何用 Sysbench 测试 TiDB
03_線性錶_鏈錶
18_Redis_Redis主从复制&&集群搭建
Why can't programmers who can only program become excellent developers?
Tidb data migration tool overview
Infra11199 database system
16_ Redis_ Redis persistence
Huffman tree: (1) input each character and its weight (2) construct Huffman tree (3) carry out Huffman coding (4) find hc[i], and get the Huffman coding of each character
05_队列
How to choose a third-party software testing organization for automated acceptance testing of mobile applications
Internet Explorer officially retired
Yolov5 code reproduction and server operation
List集合&UML图
你不知道的Set集合
搭载TI AM62x处理器,飞凌FET6254-C核心板首发上市!
可视化搭建页面工具的前世今生
List set & UML diagram
08_ 串