目录
描述
input a string(no more than 10characters),select m char from the string,output the permutation characters in lexicographic order.
输入
input a string,and integer m; m less then the length of the string. if m=0, output nothing ,and you can input another string
输出
output the permutation strings in lexicographic order.
样例输入
123
1
2
3
0
样例输出
1
2
3
12
13
23
123
思路
题意是给我们一个字符串s,给你整数m,将s分成长度为m的子串,注意这题不是全排列,而是组合数,那我们要用到递归思想
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
using namespace std;
void Combination(string input, int start, int r, string ans, vector<string>& result) {
//r代表所截取的字符串长度,ans代表正在构建的组合
if (r == 0) {
result.emplace_back(ans);
return;
}
for (int i = start; i <= input.length() - r; i++) {
ans.push_back(input[i]);
Combination(input, i + 1, r - 1, ans, result);
//递归调用取出m个字符的组合
ans.pop_back();//删除字符串最后一个元素
}
}
vector<string> getCombinations(string input, int m) {
vector<string> result;
Combination(input, 0, m, "", result);
return result;
}
int main() {
string input;
while (cin >> input) {
int m;
vector<string> combinations;
while (cin >> m && m) {
combinations = getCombinations(input, m);
for (auto s : combinations) cout << s << endl;
combinations.clear();
}
}
return 0;
}