把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
IDEA
丑数是其质因子为2,3,5 (除1和其本身外)的数
后面的一个丑数肯定是由前一个丑数*2/3/5得来的,因此采用动态规划来解答。
CODE
public class Solution {
public int GetUglyNumber_Solution(int index) {
if(index<=0)
return 0;
int[] res=new int[index];
res[0]=1;
int c2=0,c3=0,c5=0;
for(int i=1;i<index;i++){
res[i]=min(res[c2]*2,res[c3]*3,res[c5]*5);
if(res[i]==res[c2]*2) c2++;
if(res[i]==res[c3]*3) c3++;
if(res[i]==res[c5]*5) c5++;
}
return res[index-1];
}
private int min(int a,int b,int c){
int tmp=a>b?b:a;
return tmp>c?c:tmp;
}
}