1. 程式人生 > >LeetCode-313. Super Ugly Number (JAVA)超級醜數

LeetCode-313. Super Ugly Number (JAVA)超級醜數

313. 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.
(4) The nth super ugly number is guaranteed to fit in a 32-bit signed integer.

與醜數不同的是,之前求醜數是從2,3,5中找,而本題是給定的質數,求出他們的倍數的超級醜數

質數集合可以任意給定,由於我們不知道質數的個數,我們可以用一個idx陣列來儲存當前的位置,然後我們從每個子鏈中取出一個數,找出其中最小值,然後更新idx陣列對應位置,注意有可能最小值不止一個,要更新所有最小值的位置

參考:

	public int nthSuperUglyNumber(int n, int[] primes) {
		int[] dp = new int[n];
		// 第一個超級醜數是1
		dp[0] = 1;
		int[] idxPrimes = new int[primes.length];
		int counter = 1;
		while (counter < n) {
			int min = Integer.MAX_VALUE;
			for (int i = 0; i < primes.length; i++) {
				// idxPrimes[i]代表每個醜數的個數,
				// 比如醜數2題目的2,3,5,
				// idxPrimes[0]代表2的下標
				// idxPrimes[1]代表3的下標
				// idxPrimes[2]代表5的下標
				int temp = dp[idxPrimes[i]] * primes[i];
				min = min < temp ? min : temp;
			}
			// 如果min和 dp[idxPrimes[i]] * primes[i]相等,
			// 則其對應的下標++
			for (int i = 0; i < primes.length; i++) {
				if (min == dp[idxPrimes[i]] * primes[i]) {
					idxPrimes[i]++;
				}
			}
			dp[counter] = min;
			counter++;
		}
		return dp[n - 1];
	}