- #include <iostream>
- #include <math.h>
- using namespace std;
- /*数组从a[from]到a[to],b[i]=true表示a[i]被选到,假设选到的那些数和为sum,
- 函数返回M-sum.....*/
- int func(int* a, int from, int to, bool* b, int M)
- {
- if(from>to) return M;
- int k,t;
- k = func(a,from+1,to,b,M-a[from]);
- t = func(a,from+1,to,b,M);
- if(fabs(k)<fabs(t))
- {
- b[from] = true;
- return func(a,from+1,to,b,M-a[from]);//这里必须重新调用func函数,使b[]符合要求
- }
- else
- {
- b[from] = false;
- return func(a,from+1,to,b,M);
- }
- }
给定一个数组和一个数M,在数组中求一些数使它们的和最接近M------递归
最新推荐文章于 2021-11-22 14:41:32 发布