方法一暴力:牛客网 超时 no accept
class Solution {
public:
bool UglyNum(int n)
{
while (n % 2 == 0)
n /= 2;
while (n % 3 == 0)
n /= 3;
while (n %5 == 0)
n /= 5;
return n == 1 ? true : false;
}
int GetUglyNumber_Solution(int index) {
int num = 0;
if (index >= 1)
{
int UglyCount = 0;
while (UglyCount < index)
{
num++;
if (UglyNum(num))UglyCount++;
}
}
return num;
}
};
方法一DP:空间换时间 、牛客网 accept
- 不像前面那样在非丑数上浪费时间,我们可以创建一个数组,里面存着已经排好序的丑数。每个丑数都是由前面的的丑数乘以2、3、5得到。
动态规划的代码:
class Solution {
public:
int GetUglyNumber_Solution(int index) {
if (index < 1)return 0;
int p1 = 0, p2 = 0, p3 = 0;
int *Dp = new int[index];
Dp[0] = 1;
for (int i = 1; i < index; i++)
{
Dp[i] = min(min(Dp[p1] * 2, Dp[p2] * 3), Dp[p3] * 5);
if (Dp[i] == Dp[p1]*2)p1++;
if (Dp[i] == Dp[p2]*3)p2++;
if (Dp[i] == Dp[p3]*5)p3++;
}
return Dp[index - 1];
}
};