64,637
社区成员
发帖
与我相关
我的任务
分享
/////////////////////////////////////////////////////////////////////////////////////////
//!
//! \brief 用递归算法求满足特定条件的排列
//!
//! \param[in,out] list 数组元素
//! \param[in] pos 递归中正在处理第几个元素
//! \param[in] end 最后一个元素的下标
//! \param[in] condition 排列递归过程中判断数组是否满足条件
//! \param[in] output 用于输出排列数,可做其他操作
//!
/////////////////////////////////////////////////////////////////////////////////////////
void PermWithCondition( int list[], int pos, int end, int (*condition)(int[],int), void (*output)(int[],int,int) )
{
if( pos <= end )
{
int i;
for(i = pos; i <= end; i++)
{
int tmp;
tmp = list[pos], list[pos] = list[i], list[i] = tmp; //swap(&list[k], &list[i]);
if( condition(list,pos) )
{
output(list, pos, end);
PermWithCondition(list, pos + 1, end, condition, output);
}
tmp = list[pos], list[pos] = list[i], list[i] = tmp; //swap(&list[k], &list[i]);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
//
// 求满足条件的排列. 条件为相邻两个数距离在3以内
//
//////////////////////////////////////////////////////////////////////////////////////
static int g_PermCount = 0;
static void DataHandle( int list[], int pos, int end )
{
//list保存的是满足条件的序列,容易得到对应的字符串,再查字典即可实现lz的需求
if( pos >= 0 && pos <= end )
{
for(int i=0; i <= pos; ++i)
cout << list[i];
cout << "\t";
++ g_PermCount;
}
}
static int CheckCondition( int list[], int pos )
{
//递归条件判断,即7楼指出的正负3
if( 0 == pos
|| (list[pos-1]-3 <= list[pos] && list[pos] <= list[pos-1]+3) )
{
return 1;
}
return 0;
}
void PermTest( void )
{
int list[] = { 1, 2, 3, 4, 5, 6 };
PermWithCondition( list, 0, 5, CheckCondition, DataHandle );
cout << endl << "g_PermCount=" << g_PermCount << endl;
}