Leetcode 3566. Partition Array into Two Equal Product Subsets

  • [Leetcode 3566. Partition Array into Two Equal Product Subsets](#Leetcode 3566. Partition Array into Two Equal Product Subsets)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题我的实现还是比较暴力的,首先显而易见的,若要满足题目要求,则给出的数组的所有元素的乘积必然是target的平方,因此,我们可以快速由此判断该数组是否可分。

然后,在满足上述条件的前提下,我们就是要找到若干个元素使之乘积恰好为target,这个的话我们可以通过一个动态规划进行实现。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def checkEqualPartitions(self, nums: List[int], target: int) -> bool:
        prod = 1
        for num in nums:
            prod *= num
        if prod != target * target:
            return False

        n = len(nums)
        @lru_cache(None)
        def dp(idx, tgt):
            if tgt == 1:
                return True
            if idx >= n:
                return False
            if tgt % nums[idx] == 0:
                return dp(idx+1, tgt) or dp(idx+1, tgt // nums[idx])
            else:
                return dp(idx+1, tgt)

        return dp(0, target)

提交代码评测得到:耗时7ms,占用内存18.5MB。

相关推荐
leoufung7 小时前
LeetCode动态规划经典题:Unique Paths 网格路径计数详解
算法·leetcode·动态规划
放荡不羁的野指针20 小时前
leetcode150题-动态规划
算法·动态规划
水月wwww20 小时前
【算法设计】动态规划
算法·动态规划
学海一叶1 天前
论文精读-《ReAct: Synergizing Reasoning and Acting in Language Models》,2022
论文阅读·人工智能·语言模型·动态规划·agent
leoufung2 天前
LeetCode 72. Edit Distance(编辑距离)动态规划详解
leetcode·动态规划·代理模式
无尽的罚坐人生2 天前
hot 100 42. 接雨水
数据结构·算法·leetcode·动态规划··双指针
小龙报2 天前
【算法通关指南:算法基础篇 】模拟算法专题:1. 铺地毯 2. 回文日期 3. 扫雷
c语言·数据结构·c++·算法·动态规划·知识图谱·visual studio
Dream it possible!2 天前
LeetCode 面试经典 150_Kadane_环形子数组的最大和(110_918_C++_中等)(动态规划)
c++·leetcode·面试·动态规划
少许极端2 天前
算法奇妙屋(二十二)-01背包问题(动态规划)
java·算法·动态规划·背包问题·01背包
leoufung2 天前
LeetCode 188. Best Time to Buy and Sell Stock IV - 三维DP详解
算法·leetcode·动态规划