Skip to content

Commit a399942

Browse files
Update 264. 丑数 II.md
1 parent d1af9b7 commit a399942

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

Priority Queue/264. 丑数 II.md

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,33 @@ class Solution {
4949
        return (int)ans;
5050
    }
5151
}
52-
```
52+
```
53+
54+
55+
56+
动态规划:
57+
58+
定义三个指针 *p*2, *p*3, *p*5,表示下一个丑数是当前指针指向的丑数乘以对应的质因数。
59+
60+
```go
61+
func nthUglyNumber(n int) int {
62+
dp := make([]int, n + 1)
63+
dp[1] = 1
64+
x2, x3, x5 := 1, 1, 1
65+
for i := 2; i <= n; i++ {
66+
s2, s3, s5 := dp[x2] * 2, dp[x3] * 3, dp[x5] * 5
67+
dp[i] = min(min(s2, s3), s5)
68+
if dp[i] == s2 {
69+
x2++
70+
}
71+
if dp[i] == s3 { // 不能用 else if,而是用 if。因为会有重复计算
72+
x3++
73+
}
74+
if dp[i] == s5 {
75+
x5++
76+
}
77+
}
78+
return dp[n]
79+
}
80+
```
81+

0 commit comments

Comments
 (0)