#include <iostream>
using namespace std;
int total = 0;
//利用递归实现数的全排列的思想 实现_ _ _ + _ _ _ = _ _ _解法
void Permutations(int *a, const int start, const int end)//start和end分别是a的起始位置和终点位置
{
if (start == end)
{
if (a[1] * 100 + a[2] * 10 + a[3] + a[4] * 100 + a[5] * 10 + a[6] == a[7] * 100 + a[8] * 10 + a[9])
{
total++;
printf("%d%d%d+%d%d%d=%d%d%d\n", a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9]);
}
return;
}
else
{
for (int i = start; i <= end; i++)
{
swap(a[start], a[i]);//让a[i]成为首项,刚开始i=start
Permutations(a, start + 1, end);//继续交换a[start+1]和之后的元素
swap(a[start], a[i]);//每次递归完将数据交换回来
}
}
}
//算法解释:比如1 2 3
//循环
//第一个数为1 然后递归:循环
// 第二个数为2 再递归一次:由于start = end不进入循环,输出
// 第二个数为3 再递归一次:由于start = end不进入循环,输出
//第二个数为2 同理.....
//第三个数为3 同理.....
int main()
{
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Permutations(a, 1, 9);
printf("total=%d", total / 2);//从数组的下标1开始,位置0不用
system("pause");
return 0;
}
全排列思想 实现_ _ _ + _ _ _ = _ _ _解法
最新推荐文章于 2023-05-07 17:20:17 发布
