在C ++中打印所有n位严格递增的数字

在这个问题中,给我们一个数字N,我们必须打印所有n位数字,其数字从MSB到LSB急剧增加,即LSB(左)的数字应小于右数。

让我们以一个例子来了解问题-

输入-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