原题链接在这里: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).
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 }
时间: 2024-12-17 16:39:46