week 3 A-number selection problem

topic:

Given nn positive numbers, ZJM can select exactly KK of them that sums to SS. Now ZJM wonders how many ways to get it!

Input:

The first line, an integer T<=100T<=100, indicates the number of test cases. For each case, there are two lines. The first line, three integers indicate nn, KK and SS. The second line, nn integers indicate the positive numbers.

Output:

For each case, an integer indicate the answer in a independent line.

Sample Input:

1
10 3 10
1 2 3 4 5 6 7 8 9 10

Sample Output:

4

Ideas:

This question requires us to select K out of n numbers and make the sum S. If we use the method of enumeration, there are a total of 2 n times. The complexity at this time is obviously too high, so we need In the process of selecting numbers, unnecessary error conditions are eliminated, such as: K numbers have been selected but still less than S; K numbers have been selected but their sum is greater than S. According to the idea of ​​dfs depth-first search, the recursive method is used to sequentially select and deselect the n number of inputs. For unreasonable situations in the recursion process, directly return to the previous level and stop the recursive branch. When the target is reached, it returns from the last number, and adds one to the tot when returning.

Code:

#include <iostream>
#include <list>

using namespace std;

int K, tot = 0, n, S;

void solve0(int i, int sum, int *a, list<int> &res)
{
	if (res.size() == K && sum == 0)
	{
		tot++;
		return;
	}
	if (i >= n)
		return;
	if (res.size() > K || sum < 0)
		return;
	solve0(i + 1, sum, a, res);
	res.push_back(a[i]);
	solve0(i + 1, sum - a[i], a, res);
	res.pop_back();
}

int main()
{
	int cases;
	list<int> res;
	cin >> cases;
	for (int i = 0; i < cases; i++)
	{
		res.clear();
		cin >> n >> K >> S;
		int *temp = new int[n];
		for (int j = 0; j < n; j++)
			cin>>temp[j];
		tot = 0;
		solve0(0,S,temp,res);
		cout << tot << endl;
	}
    return 0; 
}
Published 32 original articles · praised 0 · visits 696

Guess you like

Origin blog.csdn.net/qq_43814559/article/details/104719320