Blue Bridge: and for the T

And for the T

Problem Description
From a zoomed ⼩ ⼀ n is an integer selected ⼀ concentration of these elements, such that they are equal to a given value and T . Each element limit selected ⼀ times, one can not ⼀ not chosen.
START input format
First frame ⾏ ⼀ positive integer n- , represents the number of elements within a set of integers.
Second shot ⾏ n integers, separated by spaces Use.
The third ⾏ ⼀ integer T , and pledged to achieve.
Output Format
If there is, dry ⾏ output, the output of each ⾏ ⼀ Solution, i.e., the selected number, arranged in order of input START.
If multiple sets of solutions, including a first priority does not output n integers; if not contain or contain, preferentially does not comprise the first output n-1 integers,
And so on. Total output last frame ⾏ ⽅ case.
Sample lose START
5
-7 -3 -2 5 9
0
Sample Output
-3 -2 5
-7 -2 9
2
Scale data and conventions
1<=n<=22 T<=maxlongint
Set of elements and do not exceed any long range
Analysis: 1 scale data n <= 22, a recursive search does not time out, to take each number or choose not to take
           2. In order to ensure compliance with the title destination time search order, the search from back to front -

 

#include <iostream>
#include <vector>
using namespace std;
vector<int> v, ans;
int n, k, cnt;
void dfs(int num, int sum) {
 if (num == -1) {
    if (sum == k && ans.size() > 0) {
        for (int i = ans.size() - 1; i >= 0; i--) {
             if (i != 0) {
                 printf("%d ", ans[i]);
             } else {
                 printf("%d\n", ans[i]);
             }
        }
        cnt++;
    }
 } else {
   dfs(num - 1, sum);
   ans.push_back(v[num]);
   dfs(num - 1, sum + v[num]);
   ans.pop_back();
 }
}
int main() {
 scanf("%d", &n);
 v.resize(n);
 for (int i = 0; i < n; i++)
      scanf("%d", &v[i]);
 scanf("%d", &k);
 dfs(n - 1, 0);
 printf("%d\n", cnt);
 return 0;
}

 

Published 736 original articles · won praise 123 · views 80000 +

Guess you like

Origin blog.csdn.net/S_999999/article/details/103390025