算法笔记DFS总结1

求最大平方和,以及构成最大平方和的子序列:

        注:本题每一个数只能使用一次。

输入

4 2 6
2 3 3 4

输出 :

2 4

20

#include <iostream>
#include <vector>
/*输入数据
4 2 6
2 3 3 4
*/
using namespace std;
vector<int>temp, ans;
int a[10010];
int n, k, x;
int maxn = 0;
void dfs(int index, int num, int sum, int sum2) {
    if (sum == x && num == k) {//和相等,数字个数相同
        if (sum2>maxn) {
            maxn = sum2;
            ans = temp;
        }
        return;
    }
    if (index==n || sum > x || num > k) {//超出和的范围,数字的范围,或者是搜索到了最后一个
        return;
    }
    temp.push_back(a[index]);//弹出
    dfs(index + 1, num + 1, sum + a[index], sum2 + a[index] * a[index]);//加上这一个数
    temp.pop_back();//回溯
    dfs(index + 1, num, sum, sum2);//不加这一个数
}

int main()
{
    cin >> n >> k >> x;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    dfs(0, 0, 0, 0);
    for (vector<int>::iterator it = ans.begin(); it < ans.end(); it++) {//迭代器的经典使用方法
        cout << *it << " ";
    }
    cout << endl;
    cout << maxn;//输出最大平方和
}

        注意迭代器的使用,以及vector之间的转换与赋值,

更改一下题目:每个数字可以使用多次,就是将dfs的代码改为:

dfs(index, num + 1, sum + a[index], sum2 + a[index] * a[index]);

 继续更新中......

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

钟一淼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值