LeetCode - super ugly numbers

Algorithm record

LeetCode topic:

  A super ugly number is a positive integer such that all of its prime factors appear in the prime number array primes.

  Given an integer n and an integer array primes, return the nth super ugly number.

  The title data guarantees that the nth super ugly number is within the range of a 32-bit signed integer.


illustrate

1. The topic

输入:n = 12, primes = [2,7,13,19]
输出:32 
解释:给定长度为 4 的质数数组 primes = [2,7,13,19],前 12 个超级丑数序列为:[1,2,4,7,8,13,14,16,19,26,28,32] 。
复制代码

2. Analysis

  • This question and the calculation method of ugly numbers are just one more variable array. The ugly number has only three prime factors, and the prime factors of this super ugly number become a variable array.
  • Just follow the practice of ugly numbers, but replace all variables with intermediate arrays for storage.
class Solution {
    public int nthSuperUglyNumber(int n, int[] primes) {
        int m = primes.length;
        int[] index = new int[m], ret = new int[n + 1], nums = new int[m];
        for(int i = 1; i <= n; i++) {
            int min = Arrays.stream(nums).min().getAsInt();
            ret[i] = min == 0 ? 1 : min;
            for(int j = 0; j < m; j++) {
                if(min == nums[j]) {
                    index[j]++;
                    nums[j] = ret[index[j]] * primes[j];
                }
            }
        }
        return ret[n];
    }
}
复制代码

Summarize

dynamic programming.

Guess you like

Origin juejin.im/post/7103885112961400862