从44、45、46...72、73共有29个数字,每次取10个数,每个数字可以重复取,要求这10个数的和为500,共有多少种情况?
比如:50取出10次就是500算符合情况。44和54各取出5次也算符合的情况,以下这些都算:
50 50 50 50 50 50 50 50 50 50
44 54 44 54 44 54 44 54 44 54
44 44 44 44 44 54 54 54 54 54
47 47 48 48 49 49 51 52 52 57
45 46 47 48 48 49 53 54 55 55
47 47 47 48 49 49 51 53 54 55
其他还有那些符合条件的情况?请穷举出来。
dfs暴搜一下就行,其实剪完枝复杂度不是很大(最深只有10层),加上输出c++也只要不到10s。
/*----------------------------------*/
/* Author : KaMtuo */
/* Email : kamtuo@qq.com */
/* Creation_time : 2022-08-08 20:06 */
/* Software : Visual Studio Code */
/*----------------------------------*/
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <queue>
#include <vector>
#include <map>
#define endl "\n"
using std::cin;
using std::cout;
using std::max;
using std::min;
using std::sort;
using std::queue;
using std::priority_queue;
using std::vector;
using std::map;
using std::string;
const int N = 30;
const int target_num = 500;
int cnt;
vector<int> in;
void dfs(int now, int sum, int to) {
if (sum == target_num && to == 10) {
cnt ++;
for (int i = 0; i < in.size(); i ++) cout << in[i] << ' ';
cout << endl;
}
if (sum >= target_num || to >= 10) return;
for (int i = now; i <= 73; i ++) {
in.push_back(i);
dfs(i, sum + i, to + 1);
in.pop_back();
}
}
int main() {
freopen("all.txt", "w", stdout);
dfs(44, 0, 0);
cout << cnt << endl;
return 0;
}
总共177376种,以下是部分方案
回溯算法
谢谢楼上的回答。可是具体怎么做呢。我用的随机算法,因为可重复,所以我每个数据复制10个放入,这样把29个数字变成290个数字进行随机抓取,每次取10个然后判断和。但是随机出来的结果太少了,比如10次都取出来是50的这个情况根本不会随机到。随机到的结果太少了。
如果用10层循环来逐个穷举来死算,那么计算量太大,根本不现实,我想应该有更智能的办法。