使用 C++ 打印所有 n 位数严格递增的数字


本例题中,给定一个数 N,要求打印所有 *n 位数*,且各位数字从高位到低位严格单调递增,即最低位 (左) 数字应小于其右边的数字。

我们通过一个例子来理解一下本题——

输入——n = 2

输出——

01 02 03 04 05 06 07 08 09 12 13 14 15 16 17 18 19 23 24 25 26 27 28 
29 34 35 36 37 38 39 45 46 47 48 49 56 57 58 59 67 68 69 78 79 89.

解释——如你所见,所有数字的左边的数字都比其右边的数字小。

要解决本题,我们将从 MSB(左位)开始依次输入数字,然后根据条件生成数字。下一个位置将包含 i+1 至 9 的数字,其中 i 是当前位置的数字。

用于实现代码逻辑的代码——

示例

 实时演示

#include <iostream>
using namespace std;
void printIncresingNumbers(int start, string out, int n) {
   if (n == 0){
      cout<<out<<" ";
      return;
   }
   for (int i = start; i <= 9; i++){
      string str = out + to_string(i);
      printIncresingNumbers(i + 1, str, n - 1);
   }
}
int main() {
   int n = 3;
   cout<<"All "<<n<<" digit strictly increasing numbers are :\n";
   printIncresingNumbers(0, "", n);
   return 0;
}

输出

All 3 digit strictly increasing numbers are −
012 013 014 015 016 017 018 019 023 024 025 026 027 028 029 034 035 036 
037 038 039 045 046 047 048 049 056 057 058 059 067 068 069 078 079 089 
123 124 125 126 127 128 129 134 135 136 137 138 139 145 146 147 148 149 
156 157 158 159 167 168 169 178 179 189 234 235 236 237 238 239 245 246 
247 248 249 256 257 258 259 267 268 269 278 279 289 345 346 347 348 349 
356 357 358 359 367 368 369 378 379 389 456 457 458 459 467 468 469 478 
479 489 567 568 569 578 579 589 678 679 689 789

更新于: 2020 年 1 月 22 日

298 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告