【发布时间】:2018-06-11 02:42:07
【问题描述】:
问题: 丑数是仅素因数为 2、3 或 5 的数。序列 1、2、3、4、5、6、8、9、10、12、15……显示前 11 个丑数。按照惯例,包括 1。
给定一个号码n,任务是找到n’th丑号码。
(https://www.geeksforgeeks.org/ugly-numbers/)
答案:以上链接中的动态编程方法
伪代码:
1 Declare an array for ugly numbers: ugly[n]
2 Initialize first ugly no: ugly[0] = 1
3 Initialize three array index variables i2, i3, i5 to point to
1st element of the ugly array:
i2 = i3 = i5 =0;
4 Initialize 3 choices for the next ugly no:
next_mulitple_of_2 = ugly[i2]*2;
next_mulitple_of_3 = ugly[i3]*3
next_mulitple_of_5 = ugly[i5]*5;
5 Now go in a loop to fill all ugly numbers till 150:
For (i = 1; i < 150; i++ )
{
/* These small steps are not optimized for good
readability. Will optimize them in C program */
next_ugly_no = Min(next_mulitple_of_2,
next_mulitple_of_3,
next_mulitple_of_5);
ugly[i] = next_ugly_no
if (next_ugly_no == next_mulitple_of_2)
{
i2 = i2 + 1;
next_mulitple_of_2 = ugly[i2]*2;
}
if (next_ugly_no == next_mulitple_of_3)
{
i3 = i3 + 1;
next_mulitple_of_3 = ugly[i3]*3;
}
if (next_ugly_no == next_mulitple_of_5)
{
i5 = i5 + 1;
next_mulitple_of_5 = ugly[i5]*5;
}
}/* end of for loop */
6.return next_ugly_no
疑问:
我不理解这种情况下的 DP 方法。
- 子问题是什么?
- 这种情况下的递归是什么?
- 子问题如何重叠?
-
我们为什么要跟踪当前的丑数?为什么不通过 2,3,5 的倍数,每个点都取最小值。
像 2,3,5。然后是 4,3,5,然后是 4,6,5..不断增加每个的倍数。
相关问题:nth ugly number(我浏览了答案,但对我提到的上述问题感到困惑。)
【问题讨论】:
-
您需要在此处发布该文章中的问题。当该链接失效时,整个问题和答案对每个人都变得毫无用处。
-
@Rob 包括在内,感谢您的建议。包括答案。如果还有问题,请告诉我。
标签: algorithm dynamic-programming