n位数字
- 真言
干脆,直接,正直,勇敢,聪明,狂妄,猥琐,还有谁?---只有我!!!
- 引言
这是我好几次做陈利人的题目,看到他有了一丝的喜爱,稍微的心动,希望爱人不要吃醋哟,哇,好酸呀。。。
- 题目
给定数字n,请给出方法,打印出所有的位数是n的数字,并且每一个数字,每一位从左到右一次变大。
例如 n=3 时,(123,124,125,···,789)
- 思路
先考虑输入n,n为数字,根据题意也只能为1~9.输入其他的要根据面试官的意图处理。这个题目首先想到无非是循环嵌套呗,但是你嵌套几层呢,n层?哥们,n是一个未知数,你傻了吧,嘿嘿。
我觉得这个题目是归为数学排列组合的,有条件的渐增的排列组合。这个题可以用递归函数去做,也可以使用非递归。我感觉非递归比较好,不会函数溢出,还是蛮棒的。那就是栈呗。栈里存放的是要求的结果。
拿个例子,看看我是怎么做的。比如说 n=3
栈的元素变化情况,如下(不全,只有开始的地方)
。。。。。。。。。。。。。。。。。。。。。。。
大家注意一下,9已经到达最大值(注意不是每一位的最大值都是9,请思考),然后把前一位加一,扩展栈规模到n一直到栈空,算法结束
- 实验
- 代码
test.cpp#include<iostream> using namespace std; bool n_number(int n); void PutOutStack(int *s,int length); // main function int main() { int i = 1; while(i <= 9) { cout<<"n="<<i<<endl; n_number(i); cout<<endl; i++; } system("pause"); return 0; } // the function to the problem bool n_number(int n) { if( n<1 || n>9 ) { cout<<"exception of n_nember input "<<endl; system("pause"); return false; } int* s = new int[n]; int length = 0; // initialize stack int i = 0; while(i < n) { s[i] = i+1 ; length ++ ; i++; } PutOutStack(s,length); // get all situations while(length != 0) { // find the first number which can grow while(length > 0) { // top of stack add 1 if( s[length-1] < 9-n+length) { s[length-1]++; break; } // stack pop else { s[length-1] = 0 ; length--; } } // stack is empty if(length == 0) break; // stack push while( length < n ) { s[length] = s[length-1]+1; length ++; } PutOutStack(s,length); } return true; } // put out the stack void PutOutStack(int *s,int length) { if(length != 0) { int i = 0; while( i < length ) { cout<<s[i]; i++; } cout<<" "; } }