- Related Questions & Answers
- All possible strings of any length that can be formed from a given string?
- Print all distinct integers that can be formed by K numbers from a given array of N numbers in C++
- Print all possible strings that can be made by placing spaces in C++
- Maximum possible time that can be formed from four digits in C++
- Print all increasing sequences of length k from first n natural numbers in C++
- Print all valid words that are possible using Characters of Array in C++
- Find all strings formed from characters mapped to digits of a number in Python
- Program to count number of palindromes of size k can be formed from the given string characters in Python
- Maximum length cycle that can be formed by joining two nodes of a binary tree in C++
- All combinations of strings that can be used to dial a number in C/C++?
- Sum of all subsets of a set formed by first n natural numbers
- Find the count of numbers that can be formed using digits 3 and 4 only and having length at max N in C++
- Print all possible sums of consecutive numbers with sum N in C++
- Print all distinct circular strings of length M in lexicographical order in C++
- Print all possible combinations of r elements in a given array of size n in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

In this problem, we are given a set of characters and a positive integer k and we have to print all possible strings of length k that can be generated using the characters of the set.

Let’s take an example to understand the problem better −

Input: set = {‘x’, ‘y’, ‘z’} , k = 2 Output: xy, xz, yz

To solve this problem, we have to find all possible sequences that can be
generated. For the set of size n, the total number of a possible string of length
k will be n^{k} (n^k). We will use a recursive call to generate the string which will start from empty string and adding character by character to it.

#include <bits/stdc++.h> using namespace std; void printKLengthString(char set[], string sequence, int n, int k) { if (k == 0){ cout<<sequence<<"\t"; return; } for (int i = 0; i < n; i++){ string newSequence; newSequence=sequence+set[i]; printKLengthString(set, newSequence, n, k - 1); } } int main() { char set[] = {'a', 'b'}; int n = 2; int k = 3; printKLengthString(set, "", n, k); }

aaa aab aba abb baa bab bba bbb

Advertisements