题目:

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

最新文章

  1. MySQL动态字符串处理DYNAMIC_STRING
  2. Linux 对比两个文本的交集和差集(comm)
  3. &lt;转&gt;DevExpress使用经验总结
  4. 2013nanjignB
  5. HDU 4435 charge-station bfs图论问题
  6. Android系统原理与源码分析(1):利用Java反射技术阻止通过按钮关闭对话框
  7. 关于MS12-020一次简单尝试
  8. 设计模式二:MVC
  9. 高仿QQ Xplan的H5页面
  10. activiti 数据库连接配置
  11. apache与nginx原理
  12. 星云STS 常用配置
  13. Guests组里的用户和其它组里的用户相比,在系统权限上有什么不同?
  14. HDU 4772 Zhuge Liang&#39;s Password (2013杭州1003题,水题)
  15. Unity动画知识之二:Animator动画状态机
  16. javascript控件(二):一个好用的表格(分页实例)
  17. 【SpringCloud微服务实战学习系列】创建应用及解析
  18. 详解iOS应用程序内使用IAP/StoreKit付费、沙盒(SandBox)测试、创建测试账号流程
  19. 实现ssh的无password登录
  20. struts2 FilterDispatcher 和 StrutsPrepareAndExecuteFilter 的区别(转)

热门文章

  1. 将SQLServer结果导出为excel文件
  2. fstab文件
  3. 【Symmetric Tree】cpp
  4. 提取html中的src 路径
  5. string::rfind
  6. codeforce 421D D. Bug in Code
  7. SGU 185 Two shortest 最短路+最大流
  8. 剑指offer--面试题23
  9. iis express 启动多个网站
  10. Ubuntu下配置Docbook环境