arrays - Subset Sum Problem [Nested Loop Solution?]
问题描述
I am working on to solve the Subset - Sum problem. Problem statement is-
Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum.
Example:
Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9
Output: True //There is a subset (4, 5) with sum 9.
I have seen different approaches to solve this problem. One of them is using recursion and other one is using Dynamic Programming.
My Question is, Why cant we solve the problem using nested loops. Each one of them considering an element and checking it one by one whether it makes a complete sum or not?
Sorry, I am new to algorithms and stuff.
解决方案
It is actually possible to solve the subset sum problem with (a lot) of nested loops. That would probably be referred to as the "non-recursive brute force naive approach", or something.
You probably will never see it, because it is a very, very, ..., very clumsy way to tackle the problem.
Indeed, you would need as many nested loops as you have elements in your input set, which would mean writing a different program for each case (1 element in your starting set, 2 elements in your starting set, etc etc ...).
Or eventually, writing a program that takes a set size N
as input, and writes a program with N
nested loops. But the result, in any case, would be as far of "good coding practices" as it can be.
The recursive approach does exactly that (it is strictly equivalent to a lot of nested loops, each recursive call send you in a 'new' loop), but much more simply and elegantly (despite doing a complete enumeration of subsets of a set, which is very, very costly). A simpler code is easier to check, easier to edit, easier to test, easier to debug ... (and on and on .... good practices are often here for a reason).
推荐阅读
- c# - 从 PEM 文件 ASP .Net 4.5 创建 X509Certificate2
- string - 在 Rust 中构建新字符串的有效方法
- r - gbm(广义提升模型)函数未正确训练
- powerbi - 在 Power BI 中将不同工作表的列相乘
- python-3.x - 将目标列合并回原始数据框
- listview - 如何删除链接到列表视图项的数据库记录?
- python - 无法在 python 中导入 snscrape 模块
- python - tqdm 安装后没有名为“tqdm”的模块
- html - 内联列表:您可以在换行符处抑制 li:after 内容吗?
- flutter - Flutter 带有自定义控制器的 ListView.builder 不会响应网页上的 PageUp/PageDown 键事件