比如
n = 2
那么从1一直输出到99
分析
直接输出,遇到大数时肯定有问题,比如n=100,存储100位的数据类型不存在。
可以利用数组来存储大数,比如n=100,可以开辟个数组 char a[101]
思路一
模拟现实中的技术方式,逢九进一
参考代码
#include <iostream>
#include <cstring>
using namespace std; bool minuxOne(char *a, int *end_index, int size)
{
if((*end_index == size - && a[size - ] == '') || *end_index < || *end_index >= size)
return false;
int tmp = size - ;
if(a[size - ] != '')
--a[size -];
else
{
a[size - ] = '';
while()
{
if(a[tmp] == '')
{
a[tmp] = '';
--tmp;
}
else
{
--a[tmp];
break;
}
}
if(a[*end_index] == '')
++*end_index;
}
return true;
} bool printNum(const int size)
{
if(size < )
return false;
char *a = new char[size];
memset(a, '', size);
int end_index = ;
while()
{
if(end_index == size - && a[size - ] == '')
break;
for(int i = ; i < size; ++i)
{
if(end_index > i && a[i] == '' )
continue;
cout << a[i];
}
cout << "\t";
if(!minuxOne(a, &end_index, size))
break;
}
delete []a;
return true;
} int main()
{
int size = ;
printNum(size);
}
结果
思路二
本质可以看作是全排列,只是前边的0别输出
#include <iostream>
using namespace std; bool print1ToMaxN(const int n);
bool print1ToMaxNRecursion(char *a, int size, int index);
bool printNum(char *a, int size);
int main()
{
int size = ;
print1ToMaxN(size);
} bool print1ToMaxN(const int size)
{
if(size <= )
return false;
char *a = new char[size];
for(int i = ; i <= ; ++i)
{
a[] = i + '';
print1ToMaxNRecursion(a, size, );
}
return true;
} bool print1ToMaxNRecursion(char *a, int size, int index)
{
if(size <= || index < )
return false;
if(index == size)
{
printNum(a, size);
return true;
}
for(int i = ; i <= ; ++i)
{
a[index] = i + '';
print1ToMaxNRecursion(a, size, index + );
}
} bool printNum(char *a, int size)
{
if(size <= )
return false;
bool IsPre0 = true;
for(int i = ; i < size; ++i)
{
if(IsPre0 && a[i] != '')
IsPre0 = false;
if(!IsPre0)
cout << a[i];
}
cout << "\t";
}
结果
分析
1. 输出问题:一开始为0不要输出,这需要输出时判断下
2. 递归全排列的本质原理:每一位字符0~0都有可能,在方位本位的时候递归遍历下一位。