This is one of those problems where the clean idea matters more than the amount of code. For 264. Ugly Number II, the solution in this repository is mainly a heap / priority queue solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: heap / priority queue, graph traversal, dynamic programming.
The notes already sitting in the source point us in the right direction:
- DP
- https://leetcode.com/problems/ugly-number-ii/discuss/69364/My-16ms-C%2B%2B-DP-solution-with-short-explanation
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are nthUglyNumber.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- The queue gives the solution a level-by-level or frontier-style traversal.
- The heap keeps the best candidate available without sorting the whole world every time.
- The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//DP
02//https://leetcode.com/problems/ugly-number-ii/discuss/69364/My-16ms-C%2B%2B-DP-solution-with-short-explanation
03//Runtime: 32 ms, faster than 36.62% of C++ online submissions for Ugly Number II.
04//Memory Usage: 7.8 MB, less than 59.06% of C++ online submissions for Ugly Number II.
05class Solution {
06public:
07 int nthUglyNumber(int n) {
08 if(n <= 0) return 0;
09 if(n == 1) return 1;
10
11 vector<int> dp(n);
12 int t2 = 0, t3 = 0, t5 = 0;
13
14 dp[0] = 1;
15 for(int i = 1; i < n; ++i){
16 dp[i] = min({dp[t2]*2, dp[t3]*3, dp[t5]*5});
17 /*
18 when we go from
19 "t2: 2, t3: 1, t5: 1, i: 4, val: 5"
20 to
21 "t2: 3, t3: 2, t5: 1, i: 5, val: 6",
22 both t2 and t3 are increased,
23 because 6 = dp[2]*2 = dp[1]*3
24 (dp[2] = 2, dp[3] = 3)
25 we increase both t2 and t3 so that 6 won't be
26 visited again
27 */
28 if(dp[i] == dp[t2]*2) ++t2;
29 if(dp[i] == dp[t3]*3) ++t3;
30 if(dp[i] == dp[t5]*5) ++t5;
31 // cout << "t2: " << t2 << ", t3: " << t3 << ", t5: " << t5 << ", i: " << i << ", val: " << dp[i] << endl;
32 }
33
34 return dp[n-1];
35 }
36};
37
38//priority queue
39//https://leetcode.com/problems/ugly-number-ii/discuss/69397/Sharing-very-simple-and-elegant-Python-solution-using-heap-with-explanation
40//Runtime: 904 ms, faster than 5.03% of C++ online submissions for Ugly Number II.
41//Memory Usage: 36.2 MB, less than 5.06% of C++ online submissions for Ugly Number II.
42class Solution {
43public:
44 int nthUglyNumber(int n) {
45 //val, last multiplied factor
46 //the smaller val should be popped first
47 priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq;
48
49 vector<vector<int>> primes = {{2,INT_MAX/2},
50 {3,INT_MAX/3},
51 {5, INT_MAX/5}};
52
53 int val = 1, fact = 1;
54 int multiplier, upperLimit;
55
56 pq.push({val, fact});
57
58 for(int i = 0; i < n; ++i){
59 vector<int> t = pq.top(); pq.pop();
60 val = t[0];
61 fact = t[1];
62 // cout << "val: " << val << ", fact: " << fact << endl;
63
64 for(int i = 0; i < primes.size(); ++i){
65 multiplier = primes[i][0];
66 upperLimit = primes[i][1];
67 /*
68 consider the number 6 = 2*3 = 3*2,
69 if can be formed of (val=2)*(multiplier=3) or
70 (val=3)*(multiplier=2),
71 so there is a duplicate.
72 To avoid the duplicate, we add a restriction that
73 current multiplier should be >= fact.
74 e.g. when val's last fact is 3, we won't multiply it by 2
75
76 note: it works like the ascending permutation of prime numbers
77 */
78 if(multiplier >= fact && val < upperLimit){
79 pq.push({val*multiplier, multiplier});
80 }
81 }
82 }
83
84 return val;
85 }
86};
Cost