[leetcode] 313. Super Ugly Number解題レポート

1542 ワード

タイトルリンク:https://leetcode.com/problems/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.
構想:ugly numberとの構想の差は多くなく、uglyシーケンスに保存するいくつかの素数の位置であり、その位置を表すugly numberにその素数が現在の数より大きいことを乗じることで、現在のどの乗算が最小のugly numberを得ることができるかを毎回比較することができる.
コードは次のとおりです.
class Solution {
public:
    int nthSuperUglyNumber(int n, vector<int>& primes) {
        vector<int> nums(n, INT_MAX), pos(primes.size(), 0);
        nums[0] = 1;
        for(int cur = 1; cur< n; cur++)
        {
            for(int i = 0; i < pos.size(); i++)//find multiple which prime can produce minimum val
                nums[cur] = min(nums[cur], nums[pos[i]] * primes[i]);
            for(int i = 0; i < pos.size(); i++)//update primes position
                while(nums[pos[i]] * primes[i] <= nums[cur])
                    pos[i]++;
        }
        return nums[n-1];
    }
};