Leetcode Note: Super uugly Number
I. Description
Write a program to find the nth super uugly number.
Super uugly 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 uugly numbers given primes = [2, 7, 13, 19] of size 4.
Note:
1 is a super uugly number for any given primes. the given numbers in primes are in ascending order. 0 <k ≤ 100, 0 <n ≤ 106, 0 <primes [I] <1000.
Ii. Question Analysis
The general idea is to write a program to find the nth "super ugly Number". The definition of the super ugly number is as follows:
The super ugly number refers to the positive number that only contains the given k quality factors. For example, given the prime number sequence with a length of 4, primes = [2, 7, 13, 19], the first 12 super ugly number sequences are: [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32]
Note:
1 is considered as a super ugly number, regardless of the given prime number list. The given prime numbers are listed in ascending order. 0 <k ≤ 100, 0 <n ≤ 106, 0 <primes [I] <1000.
One way is to use an array to record eachprimes
Number of times of the product of the inner prime number, which is stored in another Array1
Tok
Ugly number.
Iii. Sample Code
class Solution { public: int nthSuperUglyNumber(int n, vector
& primes) { int len = primes.size(); vector
index(len, 0); vector
uglyNum(n, INT_MAX); vector
temp(len); uglyNum[0] = 1; for (int i = 1; i < n; ++i) { int minj = -1; int minNum = INT_MAX; for (int j = 0; j < len; ++j) { temp[j] = primes[j] * uglyNum[index[j]]; if (temp[j] < uglyNum[i]) { minNum = temp[j]; uglyNum[i] = temp[j]; minj = j; } } for (int j = minj; j < len; ++j) { if (minNum == temp[j]) ++index[j]; } } return uglyNum[n - 1]; } };
Iv. Summary
In fact, this method requires at least 10 lines of code. In order to omit some operations, more auxiliary memory is used.