LeetCode Super Ugly Number

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Super Ugly Number相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/super-ugly-number/

题目:

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. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly numbers given primes = [2, 7, 13, 19] of size 4.

Note:
(1) 1 is a super ugly number for any given primes.
(2) The given numbers in primes are in ascending order.
(3) 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.

题解:

Ugly Number II相似. 

Time Complexity: O(nk). Space: O(n+k). k = primes.length.

AC Java:

 1 public class Solution {
 2     public int nthSuperUglyNumber(int n, int[] primes) {
 3         if(n < 1 || primes == null || primes.length == 0){
 4             return 0;
 5         } 
 6         
 7         int len = primes.length;
 8         int [] dp = new int[n];
 9         int [] ind = new int[len];
10         dp[0] = 1;
11         
12         for(int i = 1; i<n; i++){
13             int min = Integer.MAX_VALUE;
14             for(int j = 0; j<len; j++){
15                 min = Math.min(min, dp[ind[j]] * primes[j]);
16             }
17             dp[i] = min;
18             for(int j = 0; j<len; j++){
19                 if(min == dp[ind[j]] * primes[j]){
20                     ind[j]++;
21                 }
22             }
23         }
24         return dp[n-1];
25     }
26 }

 

以上是关于LeetCode Super Ugly Number的主要内容,如果未能解决你的问题,请参考以下文章

leetcode笔记:Super Ugly Number

Leetcode 313. super ugly number

LeetCode-Super Ugly Number

leetcode 313. Super Ugly Number

c_cpp super_ugly_leetcode.cpp

[leetcode] Super Ugly Number