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