Daily Coding Problem: Problem #647
/** * This problem was asked by Facebook. Given a multiset of integers, return whether it can be partitioned into two subsets whose sums are the same. For example, given the multiset {15, 5, 20, 10, 35, 15, 10}, it would return true, since we can split it up into {15, 5, 10, 15, 10} and {20, 35}, which both add up to 55. Given the multiset {15, 5, 20, 10, 35}, it would return false, since we can't split it up into two subsets that add up to the same sum. * */ class Problem_647 { /* * solution: DP, Top-Down, Memorization; * Time complexity:O(m*n), m is the total different number we have, n is the size of multiset, * Space complexity:O(n) * */ fun canPartitioned(multiset: IntArray): Boolean { val total = multiset.sum() val map = HashMap<String, Boolean>() return dfs(0,0, total, multiset, map) } private fun dfs(index: Int, sum: Int, total: Int, multiset: IntArray, map: HashMap<String, Boolean>): Boolean { //set the key for map to save sub problem result val key = "$index-$sum" if (map.containsKey(key)) { map.get(key)!! } //the sum of current part if (sum * 2 == total) { return true } if (sum > total / 2 || index > multiset.size) { return false } //check this two situation: choose or not choose the number val result = dfs(index + 1, sum, total, multiset, map) || dfs(index + 1, sum + multiset[index], total, multiset, map) map.put(key, result) return result } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)