Выведите все n-значные строго возрастающие числа

Опубликовано: 20 Января, 2022

Учитывая количество цифр 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

Ввод: n = 3
Выход: 
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

Ввод: n = 1
Выход: 0 1 2 3 4 5 6 7 8 9

Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.

The idea is to use recursion. We start from the leftmost position of a possible N-digit number and fill it from set of all digits greater than its previous digit. i.e. fill current position with digits (i to 9] where i is its previous digit. After filling current position, we recurse for next position with strictly increasing numbers. 
Below is implementation of above idea – 
 

C++

// C++ program to print all n-digit numbers whose digits
// are strictly increasing from left to right
#include <bits/stdc++.h>
using namespace std;
 
// Function to print all n-digit numbers whose digits
// are strictly increasing from left to right.
// out   --> Stores current output number as string
// start --> Current starting digit to be considered
void findStrictlyIncreasingNum(int start, string out, int n)
{
    // If number becomes N-digit, print it
    if (n == 0)
    {
        cout << out << " ";
        return;
    }
 
    // start from (prev digit + 1) till 9
    for (int i = start; i <= 9; i++)
    {
        // append current digit to number
        string str = out + to_string(i);
 
        // recurse for next digit
        findStrictlyIncreasingNum(i + 1, str, n - 1);
    }
}
 
// Driver code
int main()
{
    int n = 3;
    findStrictlyIncreasingNum(0, "", n);
    return 0;
}

Java

// Java program to print all n-digit numbers whose digits
// are strictly increasing from left to right
import java.io.*;
 
class Increasing
{
    // Function to print all n-digit numbers whose digits
    // are strictly increasing from left to right.
    // out   --> Stores current output number as string
    // start --> Current starting digit to be considered
    void findStrictlyIncreasingNum(int start, String out, int n)
    {
        // If number becomes N-digit, print it
        if (n == 0)
        {
            System.out.print(out + " ");
            return;
        }
  
        // start from (prev digit + 1) till 9
        for (int i = start; i <= 9; i++)
        {
            // append current digit to number
            String str = out + Integer.toString(i);
  
            // recurse for next digit
            findStrictlyIncreasingNum(i + 1, str, n - 1);
        }
    }
 
    // Driver code for above function
    public static void main(String args[])throws IOException
    {
        Increasing obj = new Increasing();
        int n = 3;
        obj.findStrictlyIncreasingNum(0, " ", n);
    }
}

Python3

# Python3 program to prall n-digit numbers
# whose digits are str1ictly increasing
# from left to right
 
# Function to prall n-digit numbers
# whose digits are str1ictly increasing
# from left to right.
# out --> Stores current output
#         number as str1ing
# start --> Current starting digit
#           to be considered
def findStrictlyIncreasingNum(start, out, n):
     
    # If number becomes N-digit, prit
    if (n == 0):
        print(out, end = " ")
        return
 
    # start from (prev digit + 1) till 9
    for i in range(start, 10):
         
        # append current digit to number
        str1 = out + str(i)
 
        # recurse for next digit
        findStrictlyIncreasingNum(i + 1,
                            str1, n - 1)
 
# Driver code
n = 3
findStrictlyIncreasingNum(0, "", n)
 
# This code is contributed by Mohit Kumar

C#

// C# program to print all n-digit numbers
// whose digits are strictly increasing
// from left to right
using System;
 
class GFG {
     
    // Function to print all n-digit numbers
    // whose digits are strictly increasing
    // from left to right. out --> Stores
    // current output number as string
    // start --> Current starting digit to
    // be considered
    static void findStrictlyIncreasingNum(int start,
                                  string Out, int n)
    {
         
        // If number becomes N-digit, print it
        if (n == 0)
        {
            Console.Write(Out + " ");
            return;
        }
 
        // start from (prev digit + 1) till 9
        for (int i = start; i <= 9; i++)
        {
             
            // append current digit to number
            string str = Out + Convert.ToInt32(i);
 
            // recurse for next digit
            findStrictlyIncreasingNum(i + 1, str, n - 1);
        }
    }
 
    // Driver code for above function
    public static void Main()
    {
        int n = 3;
        findStrictlyIncreasingNum(0, " ", n);
    }
}
 
// This code is contributed by Sam007.

Javascript

<script>
 
// Javascript program to print all
// n-digit numbers whose digits
// are strictly increasing from
// left to right
     
    // Function to print all
    // n-digit numbers whose digits
    // are strictly increasing
    // from left to right.
    // out   --> Stores current
    // output number as string
    // start --> Current starting
    // digit to be considered
    function findStrictlyIncreasingNum(start,out,n)
    {
        // If number becomes N-digit, print it
        if (n == 0)
        {
            document.write(out + " ");
            return;
        }
    
        // start from (prev digit + 1) till 9
        for (let i = start; i <= 9; i++)
        {
            // append current digit to number
            let str = out + i.toString();
    
            // recurse for next digit
            findStrictlyIncreasingNum(i + 1, str, n - 1);
        }
    }
     
    // Driver code for above function
    let n = 3;
    findStrictlyIncreasingNum(0, " ", n);
 
// This code is contributed by unknown2108
 
</script>

Выход:

 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

Упражнение: выведите все n-значные числа, цифры которых строго убывают слева направо.
Эта статья предоставлена Адитьей Гоэлем . Если вам нравится GeeksforGeeks, и вы хотели бы внести свой вклад, вы также можете написать статью, используя write.geeksforgeeks.org, или отправить свою статью по электронной почте: deposit@geeksforgeeks.org. Посмотрите, как ваша статья появляется на главной странице GeeksforGeeks, и помогите другим гикам.
Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.

Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по приемлемой для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .

Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.