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

Leetcode 313. Super Ugly Number

程序员文章站 2022-03-04 19:01:22
...

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Leetcode 313. Super Ugly Number

2. Solution

class Solution {
public:
    int nthSuperUglyNumber(int n, vector<int>& primes) {
        int k = primes.size();
        int index[k] = {0};
        int result[n] = {0};
        result[0] = 1;
        for(int i = 1; i < n; i++) {
            result[i] = getMinValue(index, primes, result);
        }
        return result[n - 1];
    }


private:
    int getMinValue(int index[], const vector<int>& primes, int result[]) {
        int min = INT_MAX;
        for(int i = 0; i < primes.size(); i++) {
            int value = result[index[i]] * primes[i];
            if(value < min) {
                min = value;
            } 
        }
        updateIndex(index, primes, result, min);
        return min;
    }

    void updateIndex(int index[], const vector<int>& primes, int result[], int value) {
         for(int i = 0; i < primes.size(); i++) {
            if(value == result[index[i]] * primes[i]) {
                index[i]++;
            } 
        }
    }
};

Reference

  1. https://leetcode.com/problems/super-ugly-number/description/
相关标签: Leetcode