标签:
Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first 10
ugly numbers.
Note that 1
is typically treated as an ugly number.
思路:动态规划。维持3条线路,uglynumnew=min(uglynum[k2]*2,uglynum[k3]*3,uglynum[k5]*3)(k2,k3,k5从0开始,uglynum[0]=1)。但要注意,可能会出现uglynumnew=uglynum[k2]*2=uglynum[k3]*3=uglynum[k5]*3的情况,此时,k2,k3,k5都要加1。
代码:
1 class Solution { 2 public: 3 int minnum(int a,int b,int c){ 4 return c<(min(a,b))?c:min(a,b); 5 } 6 int nthUglyNumber(int n) { 7 vector<int> uglynum(1,1); 8 int k2=0,k3=0,k5=0; 9 while(uglynum.size()<n){ 10 int temp=minnum(uglynum[k2]*2,uglynum[k3]*3,uglynum[k5]*5); 11 uglynum.push_back(temp); 12 if(temp==uglynum[k2]*2){ 13 k2++; 14 } 15 if(temp==uglynum[k3]*3){ 16 k3++; 17 } 18 if(temp==uglynum[k5]*5){ 19 k5++; 20 } 21 } 22 return uglynum[n-1]; 23 } 24 };
标签:
原文地址:http://www.cnblogs.com/Deribs4/p/5675727.html