Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Print All N Length Strings from Given Number K

Objec­tive: Given Num­ber K, Print all the strings of N length.

Exam­ple:

N = 2, K = 3

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

Approach:

This prob­lem is quite sim­i­lar to Print All Sub­sets of a given set and Print All Com­bi­na­tions of sub­set 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 recur­sive call to (N-1).
  • Base case: when n becomes 0 (means array is full).
  • See the code for bet­ter explanation.

Code:

Output:
[1, 1]
[2, 1]
[3, 1]
[1, 2]
[2, 2]
[3, 2]
[1, 3]
[2, 3]  

You may also like...