C++实现选数问题(递归)

This is a question of greedy algorithm.First I have to say that if you want to execute this program immediately in Dev ,you will meet a serious mistake:
[Error] range-based ‘for’ loops are not allowed in C++98 mode
Therefore,you must finish some compiler configuration.I’ll attach the solution at the end of the article
在这里插入图片描述Read this problem,and think of its meaning,you’ll find the answer.
在这里插入图片描述

#include<iostream>
#include<algorithm>
#include<list>
#include<stdlib.h>
using namespace std;
int elem[20];//定义一个数组存储输入的元素
int K,n,tag;
//sort(a,a+j,less<datetype>/greater<T>())
void select(int k,int sum,list<int> &res){//k
 if(res.size() == K && sum==0){//递归终点 
  for(auto it:res) {
   //cout<<it;
   tag++; 
  }
  //puts("");
  return;
 }
 //边界 
 if(k>=n) return;
 //判断合法
 if(res.size() > K || sum < 0) return;
 select(k+1,sum,res);//不选 ,相当于k++操作 
 res.push_back(elem[k]);//把第k个元素插到list尾部 
 select(k+1,sum-elem[k],res);//选 
 res.pop_back(); //删除最后一个元素 
}
int main(){
 int T,S;//Testdata,Sum
 cin>>T;//select(0,sum,list)
 for(int i=0;i<T;i++){
  tag=0; 
  list<int> ways;
  cin>>n>>K>>S;
  for(int j=0;j<n;j++)
   cin>>elem[j];
  sort(elem,elem+n,less<int>());//升序排列
  select(0,S,ways);
  cout<<tag/K<<endl; 
 }
 
 return 0; 
}

Generally speaking, I used a recursive method to solve this problem.Let me explain my part of the code in detail <~~>
maybe the part of recursion:
if you don’t choose that figure,you need make the recursion positive,and then let ‘k’ do +1 again and again,at the same time,you insert the element into the list,if you choose,you let n reduce some numbers that have already been used and let list delete last element.The most important thing you need to recognize is that this question contains DFS.If you understand DFS,I insist that you could solve this problem easily.
OK,we need to solve the problem I have mentioned:
[Error] range-based ‘for’ loops are not allowed in C++98 mode
In order to work out this question,I refer to this blog.
Reference:https://blog.csdn.net/qq_39696269/article/details/81024071
Let me actually do it again:
first, open you Dev
second,clik tools

在这里插入图片描述
third ,click Compiler options:
在这里插入图片描述
fourth,modify the parameter
在这里插入图片描述
在这里插入图片描述
And everything will be OK,wish you good luck!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值