【算法】【全排列】【八皇后】给定一串字符,输出对应字符的全排列,

给定一串字符,输出对应字符的全排列,
例如:
输入a,b,c,
输出abc,acb,bac,bca,cab,cba

依次令第一个数为:1,2,3,4
然后再递归地令:例如1的后续序列,令第二个数为2,3,4,然后再依次递归,可以看出是一个递归的结果
在这里插入图片描述

/*****
* 全排列递归
****/
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
void Permutation(char* pStr, char* pBegin) {
    
    
    if (*pBegin =='\0')
    {
    
    
        cout << pStr <<endl;  // 循环递归结束条件
    }
    else {
    
    
        for (char* pCh = pBegin; *pCh !='\0'; pCh++)
        {
    
    
            char temp = *pCh;
            *pCh = *pBegin;
            *pBegin = temp;
            Permutation(pStr, pBegin + 1);

            temp = *pCh;
            *pCh = *pBegin;
            *pBegin = temp;
        }
    }
}

void FullPermutation(char* pStr) {
    
    
    if (pStr == nullptr)
    {
    
    
        return;
    }
    Permutation(pStr, pStr);
}


void Test_FullPermutation(){
    
    
    char test[] = "123456789";
    FullPermutation(test);
}

int main()
{
    
    
    Test_FullPermutation();
}

在这里插入图片描述
在这里插入图片描述

类似地可以求解八皇后问题

#include <iostream>
using namespace std;

// 八皇后问题
bool check(int a[], int n)
{
    
    
	//多次被调用,只需一重循环 
	for (int i = 1; i <= n - 1; i++)
	{
    
    
		if ((abs(a[i] - a[n]) == n - i) || (a[i] == a[n]))
			//如果当前位置的斜上方或者斜下方有皇后,或者同一列有皇后返回false
			return false;
	}
	return true;
}

void backtrack(int a[], int n, int k, int* num)
{
    
    
	if (k > n)//找到解
	{
    
    
		for (int i = 1; i <= 8; i++)
		{
    
    
			cout << a[i]; // 输出八皇后
		}
		cout << endl;
		(*num)++;
	}
	else
	{
    
    
		for (int i = 1; i <= n; i++)
		{
    
    
			a[k] = i;
			if (check(a, k)) //检查k位置是否可以放皇后
			{
    
    
				backtrack(a, n, k + 1, num); // 可以放的话,可以检测下一位了
			}
		}
	}
}
int main()
{
    
    
	int a[] = {
    
    0, 1,2,3,4,5,6,7,8 };
	backtrack(a, 8,1,a);
}

猜你喜欢

转载自blog.csdn.net/qinglingLS/article/details/124026498