问题描述:
设有1g,2g,3g,5g,10g,20g的砝码各若干枚(其总重≤1000g),要求:
输入
a1 a2 a3 a4 a5 a6 (表示1g砝码有a1个,2g砝码有a2个,…20g砝码有a6个)
输出:
Total=N (N表示用这些砝码能称出的不同重量的个数,但不包括一个砝码也不用的情况)
输入样例:1 1 0 0 0 0
输出样例:Total=3,表示可以称出1g,2g,3g三种不同的重量
个人的java解答,非标准答案,仅供参考。
package com.qcby.mm;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
/*
*功能描述:砝码称重问题
* @author--mm
* @param weights 表示每一种砝码的重量
* @param total 表示能表示的重量的个数
* @param weightsTotal 把能表示的重量放入该容器中
* @param curweight 表示当前的重量
* @Version 1.0
*/
public class Weight {
static int[] weights= {1,2,3,5,10,20};
static Set<Integer> weightsTotal = new HashSet<>();
static int total=0;
static int curweight=0;
/**
* @author--mm
* @param n
* @param cycleIndex
* @Version 1.0
* @return
*/
static void totalWeight(int[] a,int cycleNumber) {
if(cycleNumber==6) {
return;
}
int weightNum=n[cycleNumber];
if(weightNum==0) {
totalWeight(a,cycleNumber+1);
}else {
int weight=weights[cycleNumber];
for(int i=0;i<=weightNum;i++) {
curweight+=weight*i;
if(!weightsTotal.contains(curweight)) {
total++;
weightsTotal.add(curweight);
}
totalWeight(a,cycleNumber+1);
curweight-=weight*i;
}
}
}
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
int[] a=new int[6];
for(int i=0;i<6;i++) {
a[i]=scanner.nextInt();
}
totalWeight(a,0);
System.out.print("Total="+(total-1));
}
}
注:hashset超级好用,强烈建议去学习一波。附力扣刷hashset路径
https://leetcode-cn.com/explore/learn/card/hash-table/