[leetcode] 313. Super Ugly Number 解题报告

题目链接: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];
    }
};


你可能感兴趣的:(LeetCode,array)