forked from wangcy6/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path264.UglyNumberII.cpp
130 lines (117 loc) · 3.05 KB
/
264.UglyNumberII.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <queue>
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional> // std::greater
using namespace std;
/**
class Solution {
public:
int nthUglyNumber(int n){
vector<long long> ans;
priority_queue<long long,vector<long long>,greater<long long>> Q;
unordered_map<long long,bool> visited;
Q.push(1);
visited[1]=true;
while (!Q.empty()&&ans.size()<n){
long long x=Q.top();
Q.pop();
ans.push_back(x);
if (!visited[x*2]){
Q.push(x*2);
visited[x*2]=true;
}
if (!visited[x*3]){
Q.push(x*3);
visited[x*3]=true;
}
if (!visited[x*5]){
Q.push(x*5);
visited[x*5]=true;
}
}
return ans[n-1];
}
};
**/
class Solution {
public:
int nthUglyNumber(int n)
{
priority_queue<long long,vector<long long>,greater<long long> > queue;
unordered_map<long long,bool> repeat;
queue.push(1);
repeat[1]=true;
int array[3]={2,3,5};
long long number=1;
int i=0;
while(!queue.empty()&&i++<n)
{
number=queue.top();
queue.pop();//按照从小到大顺序 greater
for(int i=0;i<3;i++)
{
long long temp=array[i]*number;
if(repeat[temp] ==false)
{
repeat[temp]=true;
queue.push(temp);
}
}
}
return number;
}
int coinChange(vector<int>& coins, int amount)
{
vector<int> dp(amount + 1,0);
for(int i=1;i<=amount;i++)
{
int temp=-1;//
for(int coin:coins)
{
if((i - coin)>=0 &&dp[i - coin] >=0)
{
if (temp ==-1)
{
temp=dp[i - coin] + 1;//第一个结果
}else
{
temp = min(temp, dp[i - coin] + 1);
}
}
}
dp[i]=temp;
}
return dp[amount];
}
};
int main()
{
cout<<nthUglyNumber(1600)<<endl;
cout<<"sizeof long = " <<sizeof(long)<<endl;
cout<<"sizeof(long long)= " <<sizeof(long long )<<endl;
int myints[]= {10,60,50,20};
std::priority_queue<int> first (myints,myints+4); //大到小
std::priority_queue<int, std::vector<int>, std::greater<int> > //小到大
second (myints,myints+4);
//最完整的声明公式(吧)形如:
//priority_queue< 结构名, vector<结构名> , greater/less<结构名> > 队列名;
//// 优先队列,默认底层容器是 vector,利用 max-heap 规则
/**
priority_queue(const value_type* __first, const value_type* __last)
: c(__first, __last) { make_heap(c.begin(), c.end(), comp); }
**/
while (!first.empty())
{
std::cout << ' ' << first.top();
first.pop();
cout<<endl;
}
while (!second.empty())
{
std::cout << ' ' << second.top();
second.pop();
cout<<endl;
}
return 0;
}