65ms Java solution using DP


  • 0
    L
    public int nthSuperUglyNumber(int n, int[] primes) {
        int[] factors = new int[primes.length];
        System.arraycopy(primes, 0, factors, 0, primes.length);
        int[] index = new int[primes.length];
        int[] uglyNums = new int[n];
        uglyNums[0] = 1;
        for(int i = 1; i < n; i++) {
            int min = minAll(factors);
            uglyNums[i] = min;
            for(int k = 0; k < factors.length; k++) {
                if(min == factors[k]) {
                    factors[k] = primes[k] * uglyNums[++index[k]];
                }
            }
        }
        return uglyNums[n-1];
    }
    
    public int minAll(int[] factors) {
        int min = factors[0];
        for(int f : factors) {
            if(f < min) {
                min = f;
            }
        }
        return min;
    }    
    

    More detailed explanation,click nthSuperUglyNumber


Log in to reply
 

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