C++回溯法实例分析

所属分类: 软件编程 / C 语言 阅读数: 88
收藏 0 赞 0 分享

本文实例讲述了C++的回溯法,分享给大家供大家参考之用。具体方法分析如下:

一般来说,回溯法是一种枚举状态空间中所有可能状态的系统方法,它是一个一般性的算法框架。

解向量a=(a1, a2, ..., an),其中每个元素ai取自一个有限序列集Si,这样的解向量可以表示一个排列,其中ai是排列中的第i个元素,也可以表示子集S,其中ai为真当且仅当全集中的第i个元素在S中;甚至可以表示游戏的行动序列或者图中的路径。

在回溯法的每一步,我们从一个给定的部分解a={a1, a2, ..., ak}开始,尝试在最后添加元素来扩展这个部分解,扩展之后,我们必须测试它是否为一个完整解,如果是的话,就输出这个解;如果不完整,我们必须检查这个部分解是否仍有可能扩展成完整解,如果有可能,递归下去;如果没可能,从a中删除新加入的最后一个元素,然后尝试该位置上的其他可能性。

用一个全局变量来控制回溯是否完成,这个变量设为finished,那么回溯框架如下,可谓是回溯大法之精髓与神器

bool finished = false;

void backTack(int input[], int inputSize, int index, int states[], int stateSize)
{
 int candidates[MAXCANDIDATE];
 int ncandidates;

 if (isSolution(input, inputSize, index) == true)
 {
 processSolution(input, inputSize, index);
 }
 else
 {
 constructCandidate(input, inputSize, index, candidates, &ncandidates);
 for (int i = 0; i < ncandidates; i++)
 {
  input[index] = candidates[i];
  backTack(input, inputSize, index + 1);
  if (finished)
  return;
 }
 }
}

不拘泥于框架的形式,我们可以编写出如下代码:

#include <iostream>

using namespace std;

char str[] = "abc";
const int size = 3;

int constructCandidate(bool *flag, int size = 2)
{
 flag[0] = true;
 flag[1] = false;

 return 2;
}

void printCombine(const char *str, bool *flag, int pos, int size)
{
 if (str == NULL || flag == NULL || size <= 0)
 return;
 
 if (pos == size)
 {
 cout << "{ ";
 for (int i = 0; i < size; i++)
 {
  if (flag[i] == true)
  cout << str[i] << " ";
 }
 cout << "}" << endl;
 }
 else
 {
 bool candidates[2];
 int number = constructCandidate(candidates);
 for (int j = 0; j < number; j++)
 {
  flag[pos] = candidates[j];
  printCombine(str, flag, pos + 1, size);
 }
 }
}

void main()
{
 bool *flag = new bool[size];
 if (flag == NULL)
 return;
 printCombine(str, flag, 0, size);
 delete []flag;
}

采用回溯法框架来计算字典序排列:

#include <iostream>

using namespace std;

char str[] = "abc";
const int size = 3;

void constructCandidate(char *input, int inputSize, int index, char *states, char *candidates, int *ncandidates)
{
 if (input == NULL || inputSize <= 0 || index < 0 || candidates == NULL || ncandidates == NULL)
 return;
 
 bool buff[256];
 for (int i = 0; i < 256; i++)
 buff[i] = false;
 int count = 0;
 for (int i = 0; i < index; i++)
 {
 buff[states[i]] = true;
 }
 for (int i = 0; i < inputSize; i++)
 {
 if (buff[input[i]] == false)
  candidates[count++] = input[i];
 }
 *ncandidates = count;
 return;
}

bool isSolution(int index, int inputSize)
{
 if (index == inputSize)
 return true;
 else
 return false;
}

void processSolution(char *input, int inputSize)
{
 if (input == NULL || inputSize <= 0)
 return;

 for (int i = 0; i < inputSize; i++)
 cout << input[i];
 cout << endl;
}

void backTack(char *input, int inputSize, int index, char *states, int stateSize)
{
 if (input == NULL || inputSize <= 0 || index < 0 || states == NULL || stateSize <= 0)
 return;
 
 char candidates[100];
 int ncandidates;
 if (isSolution(index, inputSize) == true)
 {
 processSolution(states, inputSize);
 return;
 }
 else
 {
 constructCandidate(input, inputSize, index, states, candidates, &ncandidates);
 for (int i = 0; i < ncandidates; i++)
 {
  states[index] = candidates[i];
  backTack(input, inputSize, index + 1, states, stateSize);
 }
 }
}

void main()
{
 char *candidates = new char[size];
 if (candidates == NULL)
 return;
 backTack(str, size, 0, candidates, size);
 delete []candidates;
}

对比上述两种情形,可以发现唯一的区别在于全排列对当前解向量没有要求,而字典序对当前解向量是有要求的,需要知道当前解的状态!
八皇后回溯法求解:

#include <iostream>

using namespace std;

int position[8];

void constructCandidate(int *input, int inputSize, int index, int *states, int *candidates, int *ncandidates)
{
 if (input == NULL || inputSize <= 0 || index < 0 || candidates == NULL || ncandidates == NULL)
 return;
 
 *ncandidates = 0;
 bool flag;
 for (int i = 0; i < inputSize; i++)
 {
 flag = true;
 for (int j = 0; j < index; j++)
 {
  if (abs(index - j) == abs(i - states[j]))
  flag = false;
  if (i == states[j])
  flag = false;
 }

 if (flag == true)
 {
  candidates[*ncandidates] = i;
  *ncandidates = *ncandidates + 1;
 }
 }
/*
 cout << "ncandidates = " << *ncandidates << endl;
 system("pause");*/

 return;
}

bool isSolution(int index, int inputSize)
{
 if (index == inputSize)
 return true;
 else
 return false;
}

void processSolution(int &count)
{
 count++;
}

void backTack(int *input, int inputSize, int index, int *states, int stateSize, int &count)
{
 if (input == NULL || inputSize <= 0 || index < 0 || states == NULL || stateSize <= 0)
 return;
 
 int candidates[8];
 int ncandidates;
 if (isSolution(index, inputSize) == true)
 {
 processSolution(count);
 }
 else
 {
 constructCandidate(input, inputSize, index, states, candidates, &ncandidates);
 for (int i = 0; i < ncandidates; i++)
 {
  states[index] = candidates[i];
  backTack(input, inputSize, index + 1, states, stateSize, count);
 }
 }
}

void main()
{
 //初始化棋局
 for (int i = 0; i < 8; i++)
 position[i] = i;

 int states[8];
 int count = 0;
 backTack(position, 8, 0, states, 8, count);
 cout << "count = " << count << endl;
}

希望本文所述对大家C++程序算法设计的学习有所帮助。

更多精彩内容其他人还在看

用标准c++实现string与各种类型之间的转换

这个类在头文件中定义, < sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。另外,每个类都有一个对应的宽字符集版本
收藏 0 赞 0 分享

C++如何通过ostringstream实现任意类型转string

再使用整型转string的时候感觉有点棘手,因为itoa不是标准C里面的,而且即便是有itoa,其他类型转string不是很方便。后来去网上找了一下,发现有一个好方法
收藏 0 赞 0 分享

C/C++指针小结

要搞清一个指针需要搞清指针的四方面的内容:指针的类型,指针所指向的类型,指针的值或者叫指针所指向的内存区,还有指针本身所占据的内存区
收藏 0 赞 0 分享

C++ 类的静态成员深入解析

在C++中类的静态成员变量和静态成员函数是个容易出错的地方,本文先通过几个例子来总结静态成员变量和成员函数使用规则,再给出一个实例来加深印象
收藏 0 赞 0 分享

C++类的静态成员初始化详细讲解

通常静态数据成员在类声明中声明,在包含类方法的文件中初始化.初始化时使用作用域操作符来指出静态成员所属的类.但如果静态成员是整型或是枚举型const,则可以在类声明中初始化
收藏 0 赞 0 分享

C++类静态成员与类静态成员函数详解

静态成员不可在类体内进行赋值,因为它是被所有该类的对象所共享的。你在一个对象里给它赋值,其他对象里的该成员也会发生变化。为了避免混乱,所以不可在类体内进行赋值
收藏 0 赞 0 分享

C++中的friend友元函数详细解析

友元可以是一个函数,该函数被称为友元函数;友元也可以是一个类,该类被称为友元类。友元函数的特点是能够访问类中的私有成员的非成员函数。友元函数从语法上看,它与普通函数一样,即在定义上和调用上与普通函数一样
收藏 0 赞 0 分享

static全局变量与普通的全局变量的区别详细解析

以下是对static全局变量与普通的全局变量的区别进行了详细的分析介绍,需要的朋友可以过来参考下,希望对大家有所帮助
收藏 0 赞 0 分享

C++ explicit关键字的应用方法详细讲解

C++ explicit关键字用来修饰类的构造函数,表明该构造函数是显式的,既然有"显式"那么必然就有"隐式",那么什么是显示而什么又是隐式的呢?下面就让我们一起来看看这方面的知识吧
收藏 0 赞 0 分享

教你5分钟轻松搞定内存字节对齐

随便google一下,人家就可以跟你解释的,一大堆的道理,我们没怎么多时间,讨论为何要对齐.直入主题,怎么判断内存对齐规则,sizeof的结果怎么来的,请牢记以下3条原则
收藏 0 赞 0 分享
查看更多