输出一个字符串的组合

跟上次输出一个字符串的排列类似,http://zrj.me/archives/472,要求输出一个字符串的组合,思路也是递归

#include <stdio.h>
#include <string.h>

void combine(char str[], int str_index, char res_total, char result[], int res_index)
{
	if (res_total == res_index)
	{
		for (int i=0; i<res_total; i++)
		{
			printf("%c ", result[i]);
		}
		printf("n");
	}
	else if (str_index==strlen(str))
	{
		return;
	}
	else
	{
		result[res_index] = str[str_index];
		combine(str, str_index+1, res_total, result, res_index+1);
		combine(str, str_index+1, res_total, result, res_index);
	}
}

int main()
{
	char str[100];
	char result[100];
	scanf("%s", str);
	for (int i = 1; i<=strlen(str); i++)
	{
		combine(str, 0, i, result, 0);
	}
	return 0;
}

输入输出

abcd
a
b
c
d
a b
a c
a d
b c
b d
c d
a b c
a b d
a c d
b c d
a b c d

可以发现没有考虑去重的情况,这个应该比较容易,就是预处理扫一遍,如果是 ascii 字符的话,那么把输入的 str 映射要一个位图上就可以了。

Leave a Reply

Your email address will not be published. Required fields are marked *