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
    }
}
复制代码

 

posted @   johnny_zhao  阅读(143)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示