全排列问题、八皇后问题、组合问题的递归解法

全排列问题

#include <iostream>

using namespace std;

void swap(char *a, char *b){
  char tmp = *a;
  *a = *b;
  *b = tmp;
}

void find_core(char* col, char* begin){
  if (*begin == '\0'){
    cout << col << endl;
  }
  else{
    for (char *ch = begin; *ch != '\0'; ++ch){
      swap(ch, begin);
      find_core(col, begin + 1);
      swap(ch, begin);
    }
  }
}

void find(char *col){
  find_core(col, col);
}

int main(){
  //char col[10] = "01234567";
  //char col[10] = "0123";
  char col[] = "abc";

  find(col);


  int ttt = 0;
  return 0;
}

八皇后问题

#include <iostream>

using namespace std;

//#define LENGTH 8
#define LENGTH 4

void print(int *a){
  for (int i = 0; i < LENGTH; ++i)
    cout << a[i];
  cout << endl;
}

void swap(int &a, int &b){
  int tmp = a;
  a = b;
  b = tmp;
}

bool check_valid(int *col){
  bool flag = true;
  for (int i = 0; i < LENGTH - 1; ++i){
    for (int j = i + 1; j < LENGTH; ++j){
      if (col[i] - col[j] == i - j || col[i] - col[j] == j - i){
        flag = false;
        break;
      }
    }
    if (!flag)
      break;
  }
  return flag;
}

void find_core(int *col, int k){
  if (k == LENGTH){ //if (k == LENGTH - 1)也可以
    if (check_valid(col))
      print(col);
  }
  else{
    for (int i = k; i < LENGTH; ++i){
      swap(col[i], col[k]);
      find_core(col, k + 1);
      swap(col[i], col[k]);
    }
  }
}

void find(int *col){
  find_core(col, 0);
}


int main(){
  //int col[] = {0, 1, 2, 3, 4, 5, 6, 7};
  int col[] = {0, 1, 2, 3};

  find(col);


  int ttt = 0;
  return 0;
}

组合问题

#include <iostream>

using namespace std;


void find_core(char *a, int m, int start, char *buf){
  if (m > strlen(a) - start)
    return;

  if (m == 0)
  {
    cout << buf << endl;
  }
  else
  {
    //start位置的字符为组合中的字符
    int last_len = strlen(buf);
    buf[last_len] = a[start];
    buf[last_len + 1] = '\0';
    find_core(a, m - 1, start + 1, buf);

    //start位置的字符不为组合中的字符
    buf[last_len] = '\0';
    find_core(a, m, start + 1, buf);
  }
}

void find(char *a, int m){
  char *buf = new char [m + 1];
  memset(buf, '\0', m + 1);
  find_core(a, m, 0, buf);
}

int main(){
  char a[] = "abc";

  find(a, 2);

  int ttt = 0;

  return 0;
}

    原文作者:八皇后问题
    原文地址: https://blog.csdn.net/richrdbird/article/details/51039193
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞