题目:
Given nn positive numbers, ZJM can select exactly KK of them that sums to SS. Now ZJM wonders how many ways to get it!
输入:
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.
输出:
For each case, an integer indicate the answer in a independent line.
样例:
Input
1
10 3 10
1 2 3 4 5 6 7 8 9 10
Output
4
提示:
Remember that k<=n<=16k<=n<=16 and all numbers can be stored in 32-bit intege
这题用递归的方法解决,每次都有两个分支,一个是选择这个数,一个是不选这个数,然后进入下一层,对下一个数进行判断,同时在每一步的过程中判断已选择的数个数和当前的选择的数的和,来进行剪枝。
先是写了一个结构体list,有push_back,pop_back,size几个方法
class list{
private:
int first,last;
int *l;
public:
list()//构造函数
{
first=0;
last=0;
l=new int[20];
}
void push_back(int ele)//从末尾插入
{
l[last]=ele;
last++;
}
void pop_back()//将末尾元素弹出
{
last--;
}
int size()//返回
{
return last-first;
}
};
然后是关键的递归函数func:
这是边界条件,数字个数为k并且 和为目标时说明方法+1
if(li.size()==K&&sum==0)
{
count++;
return;
}
适当的剪枝
if(num>n)
return;
if(li.size()>=K||sum<0)
return;
递归
li.push_back(a[num-1]);//选择该数,将数字压入list的最后
func(num+1,sum-a[num-1],li,a);
li.pop_back();//回溯,将之前压入的数字弹出
func(num+1,sum,li,a);//不选择该数
以下是完整代码:
#include<iostream>
using namespace std;
int count;
int n,K,S;
class list{
private:
int first,last;
int *l;
public:
list()
{
first=0;
last=0;
l=new int[20];
}
void push_back(int ele)
{
l[last]=ele;
last++;
}
void pop_back()
{
last--;
}
int size()
{
return last-first;
}
};
void func(int num,int sum,list& li,int* a)
{
if(li.size()==K&&sum==0)
{
count++;
return;
}
if(num>n)
return;
if(li.size()>=K||sum<0)
return;
li.push_back(a[num-1]);
func(num+1,sum-a[num-1],li,a);//选
li.pop_back();
func(num+1,sum,li,a);//不选
}
int main()
{
int x;
cin>>x;
for(int i=0;i<x;i++)
{
cin>>n>>K>>S;
int *a;
a=new int[n];
for(int j=0;j<n;j++)
{
cin>>a[j];
}
count=0;
list li;
func(1,S,li,a);
cout<<count<<'\n';
}
}