动态编程:找到所有成员乘积等于给定数的子集

编程入门 行业动态 更新时间:2024-10-26 08:31:21
本文介绍了动态编程:找到所有成员乘积等于给定数的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我将找到解决该问题的算法。

输入:n个整数和数字k的数组

我们必须从数组中找到一组数字,集合中所有这些数字的乘积等于k是

我认为,必须为此任务使用动态编程。但是我不知道如何使用它。

解决方案

这类似于子集和问题,需要您找出总和为值 k 的子集。

因为有解决问题的方法(您有一个子集 S ,其乘积为 k ),且仅当每个x中都有log(x)子集时集合的总和为 log(k)(相同的子集,每个元素上都有 log ),问题几乎是相同的。

但是,通常使用的DP解决方案对求和非常有效,因为元素的总和不会趋于庞大,而乘以却很。您也不能在所有元素上都使用 log 并使用它,因为数字将不是整数-子集总和的DP解决方案要求使用整数。 / p>

但是,您可以使用部分解决此问题自上而下的DP(内存) 。这是相当简单的,其操作如下:

existenceOfSubset(set,product,map): if(product == 1):返回true if(set.isEmpty()):返回false if(map.containsKey(product)):返回map .get(产品) first = set.getFirst() set = set.removeFirst()解决方案= existOfSubset(set,product,map)OR(product%first == 0? existOfSubset(set,product / first,map):false)//两种可能性的递归步骤 map.put(product,solution //存储 set.addFirst(first)//清理返回解决方案

使用 existenceOfSubset(set,product,new HashMap( ))

I will find an algorithm for this problem.

Input: array of n integers and number k

We must find a set of numbers from array, that product of all this numbers in set equals to k is

I think, I must use dynamic programming for this task. But I have no idea, how to use it.

解决方案

This is similar to the subset sum problem, where you are required to find a subset whom sum is a value k.

Since there is a solution to your problem (you have a subset S whom multiplication is k) if and only if you have a subset of log(x) for each x in the set, whom sum is log(k) (the same subset, with log on each element), the problems are pretty much identical.

However, the DP solution generally used is very efficient for sums, since sum of elements don't tend to end up huge, while multiplying does. You also cannot take log on all elements and "work with it", because the numbers will not be integers - and the DP solution to subset sum requires integers to work on.

However, you can partially solve this issue by using Top-Down DP (memoization). This is fairly simple and is done as follows:

existenceOfSubset(set, product, map): if (product== 1): return true if (set.isEmpty()): return false if (map.containsKey(product)): return map.get(product) first = set.getFirst() set = set.removeFirst() solution = existenceOfSubset(set,product,map) OR (product%first == 0?existenceOfSubset(set,product/first,map):false) //recursive step for two possibilities map.put(product,solution //memoize set.addFirst(first) //clean up return solution

invoke with existenceOfSubset(set,product,new HashMap())

更多推荐

动态编程:找到所有成员乘积等于给定数的子集

本文发布于:2023-11-30 12:18:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649920.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:乘积   子集   定数   成员   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!