第7章 递归写next_permutation

1、same 前后start 不同

2、return boolean 用于判断是否已经到达same,是否马上返回

#include<algorithm>
using namespace std;
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
const int MAXN = 100;
char org[MAXN];
char sorted[MAXN];
char ans[MAXN];
int len;
bool next_pmtt(int cur, bool aftersame)
{
	if (cur == len)
	{
		bool same = true;
		for (int i = 0; i < len; ++i)
		{
			if (ans[i] != org[i])
			{
				same = false; break;
			}
		}
		return !same;
	}
	int start = (aftersame == false) ? (strchr(sorted, org[cur]) - sorted) : 0;
	bool flag = aftersame;
	for (int i = start; i < len; ++i)
	{
		if (!i || sorted[i] != sorted[i - 1])
		{
			int numoccur = 0;
			int numtotal = 0;
			for (int j = 0; j < cur; ++j)
				if (sorted[i] == ans[j]) numoccur++;
			for (int j = 0; j < len; ++j)
				if (sorted[i] == org[j]) numtotal++;
			if (numoccur < numtotal)
			{
				ans[cur] = sorted[i];
				flag = aftersame || (ans[cur] != org[cur]); 
				// once aftersome is true, flag is always true
				if (next_pmtt(cur + 1, flag))
					return true;  // return immediately after the next permutation is found
			}
		}
	}
	return flag;
}
int main()
{
	//
	freopen("input.txt", "r", stdin);
	while (scanf("%s", org) == 1)
	{
		if (!strcmp(org, "#")) break;
		len = strlen(org);
		memcpy(sorted, org, sizeof(org));
		sort(sorted, sorted + len);
		if (next_pmtt(0, false))
		{
			for (int i = 0; i < len; ++i)
			{
				putchar(ans[i]);
			}
			putchar('\n');
		}
		else
			printf("No Successor\n");
	}
	return 0;
}

2. 位运算

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int n;
void print_set(int value)
{
	putchar('{');
	for (int element = 0; element < n; element++)
	{
		if ((1 << element) & value)
		{
			printf("%d ", element);
		}
	}
	printf("}\n");
}
int main()
{
	while (scanf("%d", &n) == 1)
	{
		for (int i = 0; i < (1 << n); ++i)
		{
			print_set(i);
		}
	}
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值