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.

鏈接: http://leetcode.com/problemset/algorithms/

題解:

超級丑數。跟丑數II很類似,只不過這次primes從2, 3, 5變成了一個size k的list。方法應該有幾種,一種是維護一個size K的min-oriented heap,heap里是k個queue,和Ugly Number II的方法一樣,取最小的那一個,然后更新其他Queue里的元素,n--,最后n = 1時循環結束。  另外一種是類似dynamic programming的方法,主要參考了larrywant2014大神的代碼。維護一個index數組,維護一個dp數組。每次遍歷更新的轉移方程非常巧妙,min = dp[[index[j]]] * primes[j]。之后再便利一次primes來update每個數在index[]中的使用次數。

Time Complexity - O(nk), Space Complexity - O(n + k).

public class Solution {
    public int nthSuperUglyNumber(int n, int[] primes) {
        if(n < 1) {
            return 0;
        }
        int len = primes.length;
        int[] index = new int[len];
        int[] dp = new int[n];
        dp[0] = 1;
        
        for(int i = 1; i < n; i++) {
            int min = Integer.MAX_VALUE;
            for(int j = 0; j < len; j++) {          // try update with all primes
                min = Math.min(dp[index[j]] * primes[j], min);
            }
            dp[i] = min;                        // find dp[i]
            for(int j = 0; j < len; j++) {      //if prices[j] is used, increase the index
                if(dp[i] % primes[j] == 0) {
                    index[j]++;
                }
            }
        }
        return dp[n - 1];
    }
}

題外話:

休假結束,又開始上班啦。不能象前幾天一樣愉快地刷題了...

Reference:

https://leetcode.com/discuss/72878/7-line-consice-o-kn-c-solution

https://leetcode.com/discuss/72835/108ms-easy-to-understand-java-solution

https://leetcode.com/discuss/74433/simple-addiction-logic-reduce-the-runtime-28ms-and-beats-77%25

http://bookshadow.com/weblog/2015/12/03/leetcode-super-ugly-number/

http://www.cnblogs.com/Liok3187/p/5016076.html

http://www.hrwhisper.me/leetcode-super-ugly-number/

http://my.oschina.net/Tsybius2014/blog/547766?p=1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM