
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print All Possible Strings of Length K in C++
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 nk (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.
Example
#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); }
Output
aaa aab aba abb baa bab bba bbb
Advertisements