Leetcode 264: Ugly Number II

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 264: Ugly Number II相关的知识,希望对你有一定的参考价值。

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number, and n does not exceed 1690.

 

 1 public class Solution {
 2     public int NthUglyNumber(int n) {
 3         if (n == 1) return 1;
 4         
 5         var dp = new long[n];
 6         dp[0] = 1;
 7         
 8         for (int i = 1; i < n; i++)
 9         {
10             dp[i] = Int32.MaxValue;
11             for (int j = i - 1; j >= 0; j--)
12             {
13                 if (dp[j] <= dp[i - 1] / 5) break;
14                 
15                 if (dp[j] > dp[i - 1] / 2) 
16                 {
17                     dp[i] = Math.Min(dp[j] * 2, dp[i]);
18                 }
19                 
20                 if (dp[j] > dp[i - 1] / 3) 
21                 {
22                     dp[i] = Math.Min(dp[j] * 3, dp[i]);
23                 }
24                 
25                 if (dp[j] > dp[i - 1] / 5) 
26                 {
27                     dp[i] = Math.Min(dp[j] * 5, dp[i]);
28                 }
29             }
30         }
31         
32         return (int)dp[n - 1];
33     }
34 }

 

以上是关于Leetcode 264: Ugly Number II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 264. Ugly Number II

leetcode 264: Ugly Number II

Leetcode 264(Ugly Number II)

LeetCode 264. Ugly Number II

[leetcode-264-Ugly Number II]

Leetcode 264: Ugly Number II