题目

解题

def nthUglyNumber(n: int) -> int:
    # 初始化 dp 数组
    dp = [0] * n
    dp[0] = 1

    # 初始化三个指针
    p2 = p3 = p5 = 0

    for i in range(1, n):
        # 计算当前三个候选丑数
        next_ugly = min(dp[p2] * 2, dp[p3] * 3, dp[p5] * 5)

        # 更新 dp 数组
        dp[i] = next_ugly

        # 移动指针
        if next_ugly == dp[p2] * 2:
            p2 += 1
        if next_ugly == dp[p3] * 3:
            p3 += 1
        if next_ugly == dp[p5] * 5:
            p5 += 1

    return dp[n - 1]


# 测试代码
n = 10
print(f"The {n}th ugly number is: {nthUglyNumber(n)}")
08-03 20:08