-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
48 lines (45 loc) · 1.05 KB
/
Solution.cs
File metadata and controls
48 lines (45 loc) · 1.05 KB
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
public class Solution
{
int ans = int.MaxValue;
public int NextBeautifulNumber(int n)
{
int[] candidate = new int[10];
for (int i = 1; i <= 6; i++) // max = 1224444 ~ 7 digits
{
candidate[i] = i;
}
BackTracking(n, 0, candidate);
return ans;
}
void BackTracking(int n, int val, int[] candidate)
{
if (val > ans) return;
if (Ok(n, val))
{
ans = Math.Min(ans, val);
return;
}
for (int i = 1; i <= 6; i++)
{
if (candidate[i] <= 0) continue;
candidate[i]--;
BackTracking(n, 10 * val + i, candidate);
candidate[i]++;
}
}
bool Ok(int n, int val)
{
if (val <= n) return false;
int[] freq = new int[10];
while (val > 0)
{
freq[val % 10]++;
val /= 10;
}
for (int i = 1; i < 10; i++)
{
if (freq[i] > 0 && freq[i] != i) return false;
}
return true;
}
}