forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SuperUglyNumber.cpp
69 lines (63 loc) · 2.09 KB
/
SuperUglyNumber.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Source : https://leetcode.com/problems/super-ugly-number/
// Author : Hao Chen
// Date : 2017-01-02
/***************************************************************************************
*
* Write a program to find the nth super ugly number.
*
* Super ugly numbers are positive numbers whose all prime factors are in the given
* prime list
* primes of size k. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32]
* is the sequence of the first 12 super ugly numbers given primes
* = [2, 7, 13, 19] of size 4.
*
* Note:
* (1) 1 is a super ugly number for any given primes.
* (2) The given numbers in primes are in ascending order.
* (3) 0 k ≤ 100, 0 n ≤ 106, 0 primes[i]
*
* Credits:Special thanks to @dietpepsi for adding this problem and creating all test
* cases.
***************************************************************************************/
// As the solution we have for the ugly number II problem
//
// int nthUglyNumber(int n) {
//
// int i=0, j=0, k=0;
// vector<int> ugly(1,1);
//
// while(ugly.size() < n){
// int next = min(ugly[i]*2, ugly[j]*3, ugly[k]*5);
// if (next == ugly[i]*2) i++;
// if (next == ugly[j]*3) j++;
// if (next == ugly[k]*5) k++;
// ugly.push_back(next);
// }
// return ugly.back();
// }
//
// The logic of solution is exacly same for both., except that instead of 3 numbers you have k numbers to consider.
//
//
//
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
vector<int> ugly(1, 1);
int len = primes.size();
vector<int> pos(len, 0);
while( ugly.size() < n ) {
int next = INT_MAX;
for(int i=0; i<len; i++) {
next = min(next, ugly[pos[i]] * primes[i]);
}
for(int i=0; i<len; i++) {
if (next == ugly[pos[i]] * primes[i]) {
pos[i]++;
}
}
ugly.push_back(next);
}
return ugly.back();
}
};