[LeetCode]264. Ugly Number II

[LeetCode]264. Ugly Number II

题目描述

[LeetCode]264. Ugly Number II_第1张图片

思路

动态规划,题目313的简单版
题目313看这里
[LeetCode]313. Super Ugly Number

代码

#include
#include
#include

using namespace std;

class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> primes = { 2,3,5 }, indexArr = { 0,0,0 }, uglyArr(n, INT_MAX);
        uglyArr[0] = 1;
        for (int i = 1; i < n; ++i) {
            for (int index = 0; index < 3; index++) uglyArr[i] = min(uglyArr[i], uglyArr[indexArr[index]] * primes[index]);
            for (int index = 0; index < 3; index++) indexArr[index] += (uglyArr[i] == uglyArr[indexArr[index]] * primes[index]);
        }
        return uglyArr[n - 1];
    }
};

int main() {
    Solution s;
    cout << s.nthUglyNumber(10) << endl;

    system("pause");
    return 0;
}

你可能感兴趣的:(leetcode)