当前位置:网站首页>C# 数组之回溯法
C# 数组之回溯法
2022-08-03 05:23:00 【全局变量】
很多数排列组合问题都可以用回溯法来解决,回溯相比上面方法的优点就是减少可行解搜索的范围,因为回溯一旦发现当前解不满足条件就会停止搜索,回溯并进入下一个分支进行搜索,比上面的方法快很多,这里使用的是回溯法中的子集树模型。对于数组中任意一个元素,先将其放入结果集中,如果当前和不超出给定和,那就继续考察下一个元素,如果超出给定和,则舍弃当前元素。如此往复,直到找到所有可行解。
首先定义一个标志位数组flag[],flag[i]如果为true,则表示a[i]在当前解中,如果flag[i]为false则表示不在。这个数组元素个数与数组a的元素个数相同。(#add,当然此标识也可以与数组元素构成结构体,然后放入数组)
string outputStr = "";bool[] flag = new bool[100];
/// <summary>
/// 回溯法
/// </summary>
/// <param name="a">a: 待搜索的数组</param>
/// <param name="n">n: 数组元素个数</param>
/// <param name="t">t: 已经存储的元素个数</param>
/// <param name="sum">sum: 给定的和</param>
public void FixedSum(int[] a,int n,int t,int sum) {
if (sum == 0)
{
Output(a, t);
outputStr += "\r\n";//分割换行
}
else
{
if (t == n)
{
return;
}
else
{
flag[t] = true;
if (sum - a[t] >= 0)
FixedSum(a, n, t + 1, sum - a[t]);
//超出
flag[t] = false;
if (sum >= 0)
FixedSum(a, n, t + 1, sum);
}
}
}
/// <summary>
/// 输出这种组合
/// </summary>
/// <param name="a"></param>
/// <param name="n"></param>
public void Output(int[] a, int n)
{
for (int i = 0; i < n; i++)
{
if (flag[i])
outputStr += a[i] + ",";
}
}
int[] a = new int[20];
for (int i = 1; i <=20; i++)
{
a[i - 1] = i;
}
FixedSum(a, 20, 0, 10);
MessageBox.Show(outputStr);//弹出结果
边栏推荐
猜你喜欢

Oracle 注释详解(--、/**/、rem)

Sentinel初次使用Demo测试

【 Nmap and Metasploit common commands 】

Oracle 密码策略详解

嵌入式实验二注意点

The ` monorepo ` ` hoist ` mechanism lead to the change of the loading configuration file path

Browser multi-threaded off-screen rendering, compression and packaging scheme

Router-view

MySql 怎么查出符合条件的最新的数据行?

动态调整web系统主题? 看这一篇就够了
随机推荐
MySQL EXPLAIN 性能分析工具详解
中国柔性制造系统(FMS)市场发展动态及未来趋势预测报告2022~2028年
Oracle null 有哪些注意事项【面试题】
【 Nmap and Metasploit common commands 】
微信小程序 自定义tabBar
Router-view
Qlik Sense 赋值详解(Set、Let)
The ` monorepo ` ` hoist ` mechanism lead to the change of the loading configuration file path
vivado遇到的问题
【命令执行与中间件漏洞】
边缘辅助无人机网络的分层联邦学习
中国认证认可服务行业“十四五”发展规划及经营模式分析报告2022~2028年
让小程序开发进入 `tailwind jit` 时代
当奈飞的NFT忘记了web2的业务安全
中国水煤浆行业“十四五”规划与运营模式分析报告2022~2028年
The result of request.getParameter is on
Navicat 解决隔一段时间不操作出现延时卡顿问题
Qlik Sense 聚合函数及范围详解(Sum、Count、All、ToTaL、{1})
Try setting CHROME_EXECUTABLE to a Chrome executable
嵌入式实验二注意点