【LeetCode 12】整数转罗马数字

如果这题按照正向的求解则非常麻烦。例如对于3749这个数字,你需要判断是千分位,还是百分位,还是十分位,还是个位?然后再判断数字大小进行组合,这么一通操作下来非常繁琐。但如果采取逆向思维解题,即按照从大到小的顺序将所有的组成成分排序,这样就能直接映射出答案了。这题背后有贪心的味道。

1. 题目

2. 分析

3. 代码

python 复制代码
class Solution:
    def intToRoman(self, num: int) -> str:
        num2roman = {1:"I", 4:"IV", 5:"V", 9:"IX", 10:"X", 40: "XL", 50:"L", 90:"XC", 100:"C", 400:"CD", 500:"D", 900:"CM", 1000:"M"}
        components = list(num2roman.keys())
        components.sort() # 从小到大的排序

        res = ""
        for i in reversed(components):
            while num >= i:
                res += num2roman[i]
                num -= i
        return res      
相关推荐
Navigator_Z10 小时前
LeetCode //C - 1278. Palindrome Partitioning III
c语言·算法·leetcode
青山木12 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
All for pursuit.15 小时前
【回溯-4】46.全排列
数据结构·c++·算法·leetcode
All for pursuit.19 小时前
【回溯-5】78.子集
数据结构·c++·算法·leetcode
代码什么用21 小时前
LeetCode-560.和为 K 的子数组
算法·leetcode
All for pursuit.21 小时前
【回溯-3】39.组合总和
数据结构·c++·算法·leetcode
yi01121 小时前
DAY19: LeetCode 28 找出字符串中第一个匹配项的下标
人工智能·笔记·python·算法·leetcode
不会就选b21 小时前
算法日常・每日刷题--<动态规划>6
数据结构·算法·leetcode
0+1112 天前
算法 --模拟
c++·算法·leetcode
Nil2082 天前
leetcode 739每日温度
算法·leetcode·职场和发展