// 创建控制台程序:
// next_permutation_algorithm.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
/* -----------------------------------------------
从第m个元素到第n个元素的全排列的算法:
存在相同元素,会重复。
-----------------------------------------------*/
int g_iCount = 0;
void Permutation(int A[], int m, int n)
{
int i, temp;
if(m == n)
{
printf("%d: ", g_iCount); //一组输出
for(i = 0; i<n; i++)
{
if(i != n-1)
printf("%d ", A[i]); //有加空格
else
printf("%d", A[i]); //没加空格
} //直接输出,因为前n-1个数已经确定,递归到只有1个数。
printf("\n"); //一组输出完毕
g_iCount++;
return;
}
else
{
for(int i=m; i<n; i++) /*进入for循环,对应第一步,注意此处是m,而不是0,因为是递归调用,对应的是第m个元素到第n个元素的全排列。*/
{
temp = A[m];
A[m] = A[i];
A[i] = temp; //交换,对应第二步
Permutation(A, m+1, n); //递归调用,对应三至五步
temp = A[m];
A[m] = A[i];
A[i] = temp; //交换,变回原来的数组
}
}
}
void Full_Array(int A[], int n)
{
Permutation(A, 0, n); //第0个元素到第n个元素的全排列
printf("\n一共有 %d 个组合\n可以看出,自己实现的函数中不会忽略对相同数字的处理,还是认为他们1和1是不一样的\n\n", g_iCount);//组合个数
}
int main(int argc, char* argv[])
{
cout << "1、调用自己实现的方法" << endl;
int a[10] = {1, 2, 3, 4, 1};
Full_Array(a, 5);
cout << "2、调用系统内部的方法,请输入一串N个数字组成的字符串" << endl;
string str;
cin >> str;
int nCount = 1;
sort(str.begin(), str.end());//必须先排序。不是数组,所以索引0呗忽略,需要加上
//cout << str << endl;
cout << "1: " << str << endl;
while (next_permutation(str.begin(), str.end()))
{
nCount++;
cout << nCount << ": " << str << endl;
}
printf("\n一共有 %d 个组合\n可以看出,自己实现的函数中会忽略对相同数字的处理,还是认为他们1和1是一样的\n\n", nCount);//组合个数
system("pause");
return 0;
}