

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 that can be formed from a set of n characters 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
- 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++
- Recursively print all sentences that can be formed from list of word lists 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++
- Find all strings formed from characters mapped to digits of a number in Python
- Program to find length of longest word that can be formed from given letters in python
- The k-th Lexicographical String of All Happy Strings of Length n in C++
- Count of sub-strings of length n possible from the given string in C++
- Program to count number of palindromes of size k can be formed from the given string characters in Python
- Print all valid words that are possible using Characters of Array in C++
- Count of strings that can be formed from another string using each character at-most once in C++
- Check whether second string can be formed from characters of first string in Python
- Maximum length cycle that can be formed by joining two nodes of a binary tree in C++
Advertisements