Leetcode 264: Ugly Number II

时间:2017-12-06 14:10:05   收藏:0   阅读:222

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 }

 

原文:http://www.cnblogs.com/liangmou/p/7992110.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!