This post is completed by 1 user

  • 0
Add to List
Hard

165. Print All N Length Strings from Given Number K

Objective: Given Number K, Print all the strings of N length.

Example:

N = 2, K = 3

[1, 1] [2, 1] [3, 1] [1, 2] [2, 2] [3, 2] [1, 3] [2, 3] [3, 3]

Approach:

This problem is quite similar to Print All Subsets of a given set and Print All Combinations of subset of size K from Given Array

  • Loop through i = 1 to K.
  • Add i to the result Array, which is the size N and make a recursive call to (N-1).
  • Base case: when n becomes 0 (means array is full).
  • See the code for better explanation.

Code:


Output:

[1, 1]
[2, 1]
[3, 1]
[1, 2]
[2, 2]
[3, 2]
[1, 3]
[2, 3]