Repeatless Numbers
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 1719 | Accepted: 726 |
Description
A repeatless number is a positive integer containing no repeated digits. For instance, the first 25 repeatless numbers are
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, …
Given an integer n, your goal is to compute the nth repeatless number.
Input
The input test file will contain multiple test cases, each consisting of a single line containing the integer n, where 1 ≤ n ≤ 1000000. The end-of-file is marked by a test case with n = 0 and should not be processed.
Output
For each input case, the program should print the nth repeatless number on a single line.
Sample Input
25
10000
0
Sample Output
27
26057
Source
一开始抱着试一试的态度从小到大顺序找了一遍,不出意外地TLE了.
然后开始写dfs,还好搜索树最多10层,时间上没问题.
不过让人纠结的地方在于我从左往右搜索,当左边不存在时用来占位的0和数字真正开始后的0不好区分,比如0000000010,
其实是10,但搜索时可能会认为0之前用过.
#include<stdio.h>
#include<string.h>
int f[1000025];
int T=-1;
int s[10];
int d[12];
int sum=0;
void dfs(int dep)
{
int i;
if (dep==10)
{
int tmp=d[1];
for (i=2;i<=10;i++) tmp=tmp*10+d[i];
T++;
f[T]=tmp;
return;
}
if (T>1000010) return;
for (i=0;i<=9;i++)
if (s[i]==0)
{
d[dep+1]=i;
sum+=i;
if (sum) s[i]++;
dfs(dep+1);
if (sum) s[i]--;
sum-=i;
}
}
void prepare()
{
memset(s,0,sizeof(s));
dfs(0);
}
int main()
{
prepare();
int N;
while (scanf("%d",&N)!=EOF && N) printf("%d
",f[N]);
return 0;
}