week3 作业A题 选数问题 递归

题目:
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';
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值