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

posted @ 2015-12-22 02:45  YRB  阅读(2310)  评论(0编辑  收藏  举报