此题,考试的时候没选这题,因为输入太多。
递归问题,最终输出比原来多1个,因为是0的关系。
直接 上答案:
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <vector>
#include <list>
#include <iostream>
#include <stack>
#include <queue>
#include <algorithm>
#include <set>
using namespace std;
std::vector<int> vec_fm_weight,vec_fm_count;
std::set<int> set_weight;
//主函数是个测试用例
void recur(int iAllWeight,int iIndex)
{
int iNextIndex;
int j;//count 索引
bool bGo = false;//是否继续递归
int iFMwei = vec_fm_weight[iIndex];
int iFMcount = vec_fm_count[iIndex];
iNextIndex = iIndex+1;
if(iNextIndex >= vec_fm_weight.size())
{
bGo = false;
}
else
{
bGo = true;
}
for(j=0;j<=iFMcount;j++)
{
int nextWeight = iAllWeight+j*iFMwei;
if(bGo)
{
recur(nextWeight,iNextIndex);
}
else
{
set_weight.insert(nextWeight);
}
}
}
int main()
{
int iFMsize;
printf("请输入砝码,总数\n");
cin>>iFMsize;
int iFM_Index;
for(iFM_Index=0;iFM_Index<iFMsize;iFM_Index++)
{
int iWeight;
printf("请输入第%d个砝码的重量\n",iFM_Index+1);
cin>>iWeight;
vec_fm_weight.push_back(iWeight);
}
iFM_Index = 0;
for(iFM_Index=0;iFM_Index<iFMsize;iFM_Index++)
{
int iCount;
printf("请输入第%d个砝码的数量\n",iFM_Index+1);
cin>>iCount;
vec_fm_count.push_back(iCount);
}
recur(0,0);
printf("可以称出的重量个数有:\n");
printf("%d",set_weight.size());
}