回溯法
来源:互联网 发布:喜欢单曲循环的人 知乎 编辑:程序博客网 时间:2024/05/16 02:34
设计算法从前m个大写字母(m≤26)种取出n个字母的所有排列(组合)(排列数)
#include<iostream>
using namespace std;
using namespace std;
char *a;
bool check(int i)
{
for(int j = 0;j < i;j++)
{
if(a[i] == a[j])//相同
{
return false;
}
}
return true;
}
bool check(int i)
{
for(int j = 0;j < i;j++)
{
if(a[i] == a[j])//相同
{
return false;
}
}
return true;
}
void output(char *a,int n)
{
for(int i = 0;i < n;i++)
{
cout<<a[i] <<" ";
}
cout<<endl;
}
{
for(int i = 0;i < n;i++)
{
cout<<a[i] <<" ";
}
cout<<endl;
}
//递归回溯法
void backTrack(int i,int n,int m)
{
if(i >= m)
{
output(a,m);
}
else
{
for(int j = 0;j < n;j++)
{
a[i] = 'A' + j;
if(check(i))
{
backTrack(i + 1,n,m);
}
}
}
}
void backTrack(int i,int n,int m)
{
if(i >= m)
{
output(a,m);
}
else
{
for(int j = 0;j < n;j++)
{
a[i] = 'A' + j;
if(check(i))
{
backTrack(i + 1,n,m);
}
}
}
}
int main()
{
int n,m;
cout<<"请输入前n个数:"<<endl;
cin>>n;
cout<<"请输入n个数中的m个数排序:"<<endl;
cin>>m;
a = new char[n];
backTrack(0,n,m);
return 0;
}
{
int n,m;
cout<<"请输入前n个数:"<<endl;
cin>>n;
cout<<"请输入n个数中的m个数排序:"<<endl;
cin>>m;
a = new char[n];
backTrack(0,n,m);
return 0;
}
阅读全文
0 0
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 专家预测产生争议导致数据中心股票下跌
- 人工智能基础了解
- Enum、EnumMap、EnumSet的用法讲解
- Git命令笔记
- ORACLE EBS DATA_BLOCK不显示数据,但Last_query可以查询到数据
- 回溯法
- Java进阶(十九)数组(下)之数组的使用
- org.apache.catalina.connector.ClientAbortException: java.net.SocketException: Connection reset by pe
- 安卓6.0权限的设置
- JS数字计算精度误差解决方法
- tomcat设置-Dfile.encoding=UTF-8 系统默认文件编码
- css基础
- tensorflow的安装教程(基于Ubuntu)
- 分享39个大数据可视化工具(数据分析必备)