算法训练:Ugly Number II

来源:互联网 发布:微艾薇h5建站 编辑:程序博客网 时间:2024/06/01 13:51

题目链接:https://leetcode.com/problems/ugly-number-ii/#/description


题目描述:

      丑数:因子只含有2,3,5的数,例如2,3,5,6,8等。要求返回第n个丑数。   

解题思路:

     从1开始判断一个数是否为丑数,若是计数加1,一直到计数等于n,返回该数字

   bool isUgly(int num) {                if (num <= 0) {            return false;        }        //判断num的因子是否只含2,3,5        while (num % 2 == 0) num /= 2;        while (num % 3 == 0) num /= 3;        while (num % 5 == 0) num /= 5;                if (num == 1) {            return true;        } else {            return false;        }    }    int nthUglyNumber(int n) {        if (n <= 1) {            return 1;        }        int count = 0;        for (int i = 1; ; i++) {                        if (isUgly(i)) {                count++;                if (count == n) {                    return i;                }            }         }    }
       动态规划的方法:

       丑数序列可以拆分为下面3个子列表:

         factor=2: 1×2, 2×2, 3×2, 4×2, 5×2,...

         factor=3: 1×3, 2×3, 3×3, 4×3, 5×3, …

         factor=5: 1×5, 2×5, 3×5, 4×5, 5×5, …

       观察上述三个列表,可以发现每个子列表都是一个丑数分别乘以2,3,5。

       分别用t2,t3,t5来记录当前三个序列的下标,然后比较三者,最小的数先加入丑数序列

       边界条件:result[0]=1。

       推导式:result[i]=min(result[t2]*2,result[t3]*3,result[t5]*5),result[i]保存的是第i+1个丑数。

    int nthUglyNumber(int n) {        if(n <= 0) return 0;vector<int> result(n, 1); //全部初始化为1int t2 = 0, t3 = 0, t5 = 0; //初始下标均从0开始for(int i = 1; i < n; ++i){   result[i] = min(result[t2]*2, min(result[t3]*3, result[t5]*5));   if(result[i] == result[t2]*2) t2++; //判断是否是factor=2的序列对应的下标需要向后移动   if(result[i] == result[t3]*3) t3++;   if(result[i] == result[t5]*5) t5++;}return result[n-1];    }

运行结果:

Your Input
10
Your answer
12
Expected answer
12











0 0
原创粉丝点击