码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 264: Ugly Number II

时间:2017-12-06 14:21:49      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:var   public   for   exce   leetcode   not   nbsp   bsp   long   

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

标签:var   public   for   exce   leetcode   not   nbsp   bsp   long   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!