Share my C++ solution,similar to "Ugly Number II",easy to understand


  • 0
    V
    class Solution {
    public:
        int nthSuperUglyNumber(int n, vector<int>& primes) {
            int i = 0, j = 0, k = primes.size(), min = 0;
            vector<int> superUglyNumbers(n, 0);
            vector<int> idx(k, 0);
            
            superUglyNumbers[0] = 1;
            
            for (i = 1; i < n; ++i)
            {
                min = superUglyNumbers[idx[0]] * primes[0];
                
                for (j = 1; j < k; ++j)
                {
                    if (min > superUglyNumbers[idx[j]] * primes[j])
                        min = superUglyNumbers[idx[j]] * primes[j];
                }
                
                superUglyNumbers[i] = min;
                
                for (j = 0; j < k; ++j)
                {
                    if (min == superUglyNumbers[idx[j]] * primes[j])
                        ++idx[j];
                }
            }
                
            return superUglyNumbers[n-1];
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.