欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[leetcode]313. Super Ugly Number

程序员文章站 2022-03-07 18:12:36
...

[leetcode]313. Super Ugly Number


Analysis

missing—— [每天刷题并不难0.0]

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.
[leetcode]313. Super Ugly Number

Explanation:

This problem is an extenssion of “ugly number” and “ugly number 2”. An new ugly number is previous ugly number multiply the factor in primes, and we take the minmum result as our newly ugly number.

Implement

class Solution {
public:
    int nthSuperUglyNumber(int n, vector<int>& primes) {
        vector<int> res;
        res.push_back(1);
        int len = primes.size();
        vector<int> idx(len, 0);
        while(res.size() < n){
            vector<int> tmp;
            int mn = INT_MAX;
            for(int i=0; i<len; i++)
                tmp.push_back(res[idx[i]]*primes[i]);
            for(int i=0; i<len; i++)
                mn = min(mn, tmp[i]);
            for(int i=0; i<len; i++){
                if(mn == tmp[i])
                    idx[i]++;
            }
            res.push_back(mn);
        }
        return res.back();
    }
};