Problem P27. [算法课回溯]目标和

回溯法比较简单易懂,耗时比较长,也能过。有动态规划的解法大家可以自己想一想。

#include<iostream>
#include<bits/stdc++.h>
#include<cstdio>
#include<string>

using namespace std;

int cnt = 0;

void callBackSeach(vector<int> &nums, int idx, int sum, int target) {
    if (idx == nums.size()) {
        if (sum == target) {
            cnt++;
        }
        return;
    }
    callBackSeach(nums, idx+1, sum+nums[idx], target);
    callBackSeach(nums, idx+1, sum-nums[idx], target);
};

int main()
{
    vector<int> nums;
    int target;
    while (1) {
        int n;
        int ret = scanf("%d", &n);
        if (ret == EOF) {
            break;
        }
        nums.push_back(n);
    }
    target = nums.back();
    nums.pop_back();
    callBackSeach(nums, 0, 0, target);
    cout << cnt << endl;
    return 0;
}

posted @ 2022-10-14 22:18  白缺  阅读(65)  评论(0编辑  收藏  举报