您的位置:首页 > 其它

Print all possible strings of length k that can be formed from a set of n characters

2015-01-26 19:16 399 查看
Given a set of characters and a positive integer k, print all possible strings of length k that can be formed from the given set.

Examples:

Input: set[] = {'a', 'b'}, k = 3Output:aaaaababaabbbaababbbabbbInput: set[] = {'a', 'b', 'c', 'd'}, k = 1Output:abcd

Given a set of characters and a positive integer k, print all possible strings of length k that can be formed from the given set.

Examples:
Input:
set[] = {'a', 'b'}, k = 3

Output:
aaa
aab
aba
abb
baa
bab
bba
bbb

Input:
set[] = {'a', 'b', 'c', 'd'}, k = 1
Output:
a
b
c
d


Input: set[] = {'a', 'b'}, k = 3Output:aaaaababaabbbaababbbabbbInput: set[] = {'a', 'b', 'c', 'd'}, k = 1Output:abcd

//

// main.cpp

// stringOutput

//

// Created by Libin Liang on 1/26/15.

// Copyright (c) 2015 com.libin. All rights reserved.

//

#include <iostream>

#include <string>

#include <vector>

using namespace
std;

void printVtr(vector<char> &vtr)
{

for (int i=0; i<vtr.size(); i++)

printf ("%c ", vtr[i]);

printf("\n");

return;
}

void foo(string str,
int k, vector<char> &vtr)
{

if (k == 0)
{

printVtr(vtr);

return;
}

for (int i=0; i<str.size(); i++)
{
vtr.push_back(str.at(i));

foo(str, k-1, vtr);
vtr.pop_back();
}
}

void outputString(string str,
int k)
{

if (str.size() ==
0 || k <= 0)

return;

vector<char> vtr;

for (int i=0; i<str.size(); i++)
{
vtr.push_back(str.at(i));

foo(str, k-1, vtr);
vtr.pop_back();
}

return;

}

int main(int argc,
const char * argv[]) {

outputString("ab",
3);

return 0;
}

Input: set[] = {'a', 'b'}, k = 3Output:aaaaababaabbbaababbbabbbInput: set[] = {'a', 'b', 'c', 'd'},
k = 1Output:abcd
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐