Combination(n,m)

目录

描述

输入

输出

样例输入

样例输出


描述

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值