0
点赞
收藏
分享

微信扫一扫

【算法】递归回溯算法(C++源码)

罗子僧 2022-10-18 阅读 128


【算法】递归回溯算法(C++源码)

  • ​​一、任务描述:​​
  • ​​二、要求​​
  • ​​三、运行结果截图:​​
  • ​​四、源代码(C++)​​

一、任务描述:

采用递归回溯法设计一个算法,求从1~n的n个整数中取出m个元素的排列,要求每个元素最多只能取一次。例如,n=3,m=2的输出结果是(1,2),(1,3),(2,1),(2,3), (3,1),(3,2)。

二、要求

选取不同的n和m测试所设计的上述算法

三、运行结果截图:

【算法】递归回溯算法(C++源码)_算法


【算法】递归回溯算法(C++源码)_递归_02


【算法】递归回溯算法(C++源码)_c++_03

四、源代码(C++)

#include <iostream>

using namespace std;

int cs,n,m;
int a[100];
void f(int t)
{
int i,j;
if(cs==m)
{
for(i=1;i<=m;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
cs--;
}
else
{
for(i=1;i<=n;i++)
{
for(j=1;j<=cs;j++)
{
if(a[j]==i)
break;
}
if(j>cs)
{
cs++;
a[cs]=i;
f(i);
}
}
cs--;
}
}

int main()
{
cout<<"Please enter the number of 'n' :";
cin>>n;
cout<<"Enter the number of elements to take out the arrangement 'm' :";
cin>>m;
cs=0;
f(0);
return 0;
}


举报

相关推荐

0 条评论