且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

剑指Offer之打印1到最大的N位数

更新时间:2021-09-04 13:25:14

题目描述:

给定一个数字N,打印从1到最大的N位数。

输入:

每个输入文件仅包含一组测试样例。
对于每个测试案例,输入一个数字N(1<=N<=5)。

输出:

对应每个测试案例,依次打印从1到最大的N位数。

样例输入:
1
样例输出:
1
2
3
4
5
6
7
8
9

/*********************************
*   日期:2013-11-11
*   作者:SJF0115
*   题号: 题目1515:打印1到最大的N位数
*   来源:http://ac.jobdu.com/problem.php?pid=1515
*   结果:AC
*   来源:剑指Offer
*   总结:
**********************************/
#include<iostream>
#include<stdio.h>
#include<malloc.h>
#include<string>
using namespace std;
/*
* n     最大的n位
* index 递归下标
*/
void FullPermutation(char *number,int n,int index){
    int i;
    //最后一位停止递归生成一种全排列
    if(index == n){
        int flag = 1;
        for(i = 0;i < n;i++){
            //排除前导0
            if(flag && number[i] == '0'){
                continue;
            }
            else{
                flag = 0;
                printf("%c",number[i]);
            }
        }
        if(flag == 0){
            printf("\n");
        }
        return;
    }
    else{
        for(i = 0;i < 10;i++){
            number[index] = i + '0';
            FullPermutation(number,n,index + 1);
        }
    }
}

void OutPutNumber(int n){
    if(n < 0){
        return;
    }
    else{
        char *number = new char[n + 1];
        number[n] = '\0';
        //全排列
        FullPermutation(number,n,0);
    }
}

int main()
{
	int i,n;
	while(scanf("%d",&n) != EOF){
        OutPutNumber(n);
	}
    return 0;
}


【解析】

上题完全可以看成N个数的全排列