313.Super Ugly Number
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]
< 1000.
Credits:
Special thanks to @peisi for adding this problem and creating all test cases.
思路:此题可以利用dp来完成。设dp[i]代表第i个Super Ugly Number,index[i]表示第i个质数应该和第几个质数相乘。初始化设置dp[0]=0,index[i]为0 i∈[0,primes.size())。设置cur=1,代表正在生成第cur个super ugly number,进入循环,直至cur=n退出。求取dp[index[j]]*primes[j] j∈[0,primes.size())中的最小值,记录最小值min和最小值取的prime的下标minIndex。因为prime[min]已经和dp[minIndex]相乘过了,所以接下来应该和后一位super ugly number相乘,设置index[minIndex]++。因为可能求出的最小值min和dp[i-1]相同,需要跳过这种情况,只有不重复时,才将dp[cur]设置为min,并设置cur++,继续求取下一个super ugly number。
-
class Solution { public: int nthSuperUglyNumber(int n, vector<int>& primes) { vector<int> index(primes.size(),0); vector<int> dp(n); dp[0]=1; int len=primes.size(); int minIndex; int cur=1; while(cur<n){ int min=INT_MAX; for(int j=0;j<len;j++){ int tmp=dp[index[j]]*primes[j]; if(tmp<min){ min=tmp; minIndex=j; } } index[minIndex]++; if(dp[cur-1]!=min){ dp[cur]=min; cur++; } } return dp[n-1]; } };