题解 | #称砝码#

太坑了,这题测试数据中有输入不规范的,需要处理输入时Trim()一下😂

处理输入后,按照每个重量的砝码的数量,把所有砝码塞到一个容器中,完成初步处理。

然后是重头戏:
    1、求得所有组合方式并且去重。去重那就很自然想到用Dictionary或者和HashSet当做容器。由于需要记录的数据只有“某种组合方式的总重”这一个,所以选用HashSet<int>。
    2、然后是求所有可能总重,核心算法如下:
        HashSet<int> combinations = new Hashset<int> { 0 }; // 初始化先将 选取0个砝码 的情况计入
        foreach weight in all_weights:
            foreach combo in combinations:
                combinations.Add(combo + weight )
        return combinations.Count
        每次向HashSet加入一个新的砝码的时候,都会将新砝码和 已经尝试过的 去重的 组合 组合起来,如果形成新组合,那么HashSet就会扩容;否则会被去重。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ProjectSample
{
    //HJ41
    class Program
    {
        static void Main(string[] args)
        {
            int variation = int.Parse(Console.ReadLine());
            string wei_str = Console.ReadLine().Trim();
            int[] weights = wei_str.Split(' ')
                .Select(o => int.Parse(o)).ToArray();
            string cou_str = Console.ReadLine().Trim();
            int [] counts = cou_str.Split(' ')
                .Select(o => int.Parse(o)).ToArray();

            List<int> weights_with_rep = new List<int>();
            for (int i = 0; i < counts.Length; i++) 
            {
                var c = counts[i];

                for (int j = 0; j < c; j++) 
                {
                    weights_with_rep.Add(weights[i]);
                }
            }

            HashSet<int> tW= new HashSet<int> { 0 };
            for (int i = 0; i < weights_with_rep.Count; i++) 
            {
                foreach (var w in tW.ToList()) 
                {
                    tW.Add(w + weights_with_rep[i]);
                }
            }

            Console.WriteLine(tW.Count);
        }
    }
}


全部评论

相关推荐

07-11 11:15
中南大学 Java
好可爱的hr姐姐哈哈哈哈
黑皮白袜臭脚体育生:兄弟们貂蝉在一起,吕布开了
点赞 评论 收藏
分享
自学java狠狠赚一...:骗你点star的,港卵公司,记得把star收回去
点赞 评论 收藏
分享
05-29 20:34
门头沟学院 C++
KarlAllen:得做好直接春招的准备。学历差的话,一是面试要求会比学历好的严格不少,二是就算面试通过了也会被排序。总之暑期和秋招对于学历差的就是及其不友好
无实习如何秋招上岸
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 13:15
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务