子集和與一個整數相等算法_背包問題的一個變體:如何解決Java中的分區相等子集和問題...

子集和與一個整數相等算法

by Fabian Terh

由Fabian Terh

Previously, I wrote about solving the Knapsack Problem (KP) with dynamic programming. You can read about it here.

之前,我寫過有關使用動態編程解決背包問題(KP)的文章。 你可以在這里閱讀 。

Today I want to discuss a variation of KP: the partition equal subset sum problem. I first saw this problem on Leetcode — this was what prompted me to learn about, and write about, KP.

今天,我要討論KP的一種變體: 分區相等子集和問題 。 我首先在Leetcode上看到了這個問題-這就是促使我學習和撰寫KP的原因。

This is the problem statement (reproduced partially without examples):

這是問題說明(部分復制而沒有示例):

Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
給定一個僅包含正整數的非空數組,請確定該數組是否可以劃分為兩個子集,以使兩個子集中的元素之和相等。

For the full problem statement, with constraints and examples, check out the Leetcode problem.

有關完整的問題說明(包括約束和示例),請查看Leetcode問題 。

動態編程 (Dynamic programming)

Like with KP, we’ll be solving this using dynamic programming. Since this is a variation of KP, the logic and methodology is largely similar.

與KP一樣,我們將使用動態編程來解決此問題。 由于這是KP的變體,因此邏輯和方法學非常相似。

(Solution)

We will house our solution in a method that returns a boolean — true if the array can be partitioned into equal subsets, and false otherwise.

我們將解決方案包含在一個返回布爾值的方法中—如果可以將數組劃分為相等的子集,則返回true,否則返回false。

步驟1:防止奇數數組和 (Step 1: Guarding against odd array sum)

Trivially, if all the numbers in the array add up to an odd sum, we can return false. We only proceed if the array adds up to an even sum.

瑣碎地,如果數組中的所有數字加起來為奇數和,則可以返回false。 我們僅在數組加和為偶數時繼續進行。

步驟2:建立表格 (Step 2: Creating the table)

Next, we create the table.

接下來,我們創建表。

Table rows represent the set of array elements to be considered, while table columns indicate the sum we want to arrive at. Table values are simply boolean values, indicating whether a sum (column) can be arrived at with a set of array elements (row).

表行表示要考慮的一組數組元素,而表列表示我們要達到的總和。 表值只是布爾值,指示是否可以通過一組數組元素(行)得出總和(列)。

Concretely, row i represents a set of array elements from indices 0 to (i-1). The reason for this offset of 1 is because row 0 represents an empty set of elements. Therefore, row 1 represents the first array element (index 0), row 2 represents the first two array elements (indices 0–1), and so on. In total, we create n + 1 rows, inclusive of 0.

具體而言,第i行代表從索引0到( i -1)的一組數組元素。 偏移量為1的原因是因為行0代表一組空元素。 因此,第1行代表第一個數組元素(索引0),第2行代表前兩個數組元素(索引0-1),依此類推。 我們總共創建n + 1行,包括0。

We only want to know if we can sum up exactly to half the total sum of the array. So we only need to create totalSum / 2 + 1 columns, inclusive of 0.

我們只想知道是否可以精確地求和該數組總和的一半。 因此,我們只需要創建totalSum / 2 + 1列(包括0)即可。

步驟3:預先填寫表格 (Step 3: Pre-filling the table)

We can immediately begin filling the entries for the base cases in our table — row 0 and column 0.

我們可以立即開始在表中填充基本案例的條目-第0行和第0列。

In the first row, every entry — except the first — must be false. Recall that the first row represents an empty set . Naturally, we are unable to arrive at any target sum — column number — except 0.

在第一行中,除第一行外,每個條目都必須為false 。 回想一下,第一行代表一個空集。 自然,我們無法得出除0以外的任何目標總數(列號)。

In the first column, every entry must be true. We can always,trivially, arrive at a target sum of 0, regardless of the set of elements we have to work with.

在第一列中,每個條目都必須為true 。 無論我們要使用什么元素集,我們總是可以輕松地達到目標總和0。

步驟4:建立表格(問題的癥結) (Step 4: Building the table (the crux of the problem))

Some entry in the table at row i and column j is true (attainable) if one of the following three conditions are satisfied:

如果滿足以下三個條件之一,則第i行和第j列中表中的某些條目為true (可達到):

  1. the entry at row i-1 and column j is true. Recall what the row number represents. Therefore, if we are able to attain a particular sum with a subset of the elements that we have presently, we can also attain that sum with our current set of elements — by simply not using the extra elements. This is trivial. Let’s call this prevRowIsTrue.

    i -1行和第j列的條目為true 。 回憶一下行號代表什么。 因此,如果我們能夠使用當前元素的一個子集獲得一個特定的總和,那么我們也可以使用我們當前的元素集來獲得該總和-只需不使用額外的元素即可。 這是微不足道的。 我們將此prevRowIsTrue

  2. The current element is exactly the sum we want to attain. This is also trivially true. Let’s call this isExactMatch.

    當前元素正是我們想要獲得的總和。 這一點也是正確的。 我們將此isExactMatch

  3. If the above two conditions are not satisfied, we have one remaining way of attaining our target sum. Here, we use the current element — the additional element in the set of elements in our current row compared to the set of elements in the previous row — and check that we are able to attain the remainder of the target sum. Let’s call this canArriveAtSum.

    如果不滿足上述兩個條件,則我們還有另一種方法來達到目標??總和。 在這里,我們使用當前元素(當前行元素集中的上一個元素與前一行元素集相比的其他元素),并檢查是否能夠達到目標總和的其余部分。 我們將此canArriveAtSum

Let’s unpack condition 3. We can only use the current element if it is less than our target sum. If they’re equal, condition 2 would be satisfied. If it’s larger, we can’t use it. Therefore, the first step is to ensure that current element < target sum.

讓我們解壓縮條件3。 如果當前元素小于目標總和,我們只能使用它。 如果它們相等,則將滿足條件2。 如果更大,我們將無法使用。 因此,第一步是確保當前元素<目標總和。

After using our current element, we are left with the remainder of our target sum. We then check if that is attainable by checking the corresponding entry in the row above.

使用完當前元素后,剩下剩下的目標總和。 然后,我們通過檢查上一行中的相應條目來檢查是否可以實現。

As with regular KP, we want to progressively build our table from the bottom-up. We start with the base cases, until we arrive at our final solution.

與常規KP一樣,我們希望從下至上逐步構建表格。 我們從基本案例開始,直到得出最終解決方案。

步驟5:返回答案 (Step 5: Returning the answer)

We simply return return mat[nums.length][totalSum / 2].

我們只返回return mat[nums.length][totalSum / 2]

工作代碼 (Working code)

Thanks for reading!

謝謝閱讀!

翻譯自: https://www.freecodecamp.org/news/a-variation-on-the-knapsack-problem-how-to-solve-the-partition-equal-subset-sum-problem-in-java-7e0fc047f19b/

子集和與一個整數相等算法

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391892.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391892.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391892.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

matplotlib圖表介紹

Matplotlib 是一個python 的繪圖庫&#xff0c;主要用于生成2D圖表。 常用到的是matplotlib中的pyplot&#xff0c;導入方式import matplotlib.pyplot as plt 一、顯示圖表的模式 1.plt.show() 該方式每次都需要手動show()才能顯示圖表&#xff0c;由于pycharm不支持魔法函數&a…

到2025年將保持不變的熱門流行技術

重點 (Top highlight)I spent a good amount of time interviewing SMEs, data scientists, business analysts, leads & their customers, programmers, data enthusiasts and experts from various domains across the globe to identify & put together a list that…

spring—SpringMVC的請求和響應

SpringMVC的數據響應-數據響應方式 頁面跳轉 直接返回字符串 RequestMapping(value {"/qq"},method {RequestMethod.GET},params {"name"})public String method(){System.out.println("controller");return "success";}<bea…

Maven+eclipse快速入門

1.eclipse下載 在無外網情況下&#xff0c;無法通過eclipse自帶的help-install new software輸入url來獲取maven插件&#xff0c;因此可以用集成了maven插件的免安裝eclipse(百度一下有很多)。 2.jdk下載以及環境變量配置 JDK是向前兼容的&#xff0c;可在Eclipse上選擇編譯器版…

源碼閱讀中的收獲

最近在做短視頻相關的模塊&#xff0c;于是在看 GPUImage 的源碼。其實有一定了解的伙伴一定知道 GPUImage 是通過 addTarget 鏈條的形式添加每一個環節。在對于這樣的設計贊嘆之余&#xff0c;想到了實際開發場景下可以用到的場景&#xff0c;借此分享。 我們的項目中應該有很…

馬爾科夫鏈蒙特卡洛_蒙特卡洛·馬可夫鏈

馬爾科夫鏈蒙特卡洛A Monte Carlo Markov Chain (MCMC) is a model describing a sequence of possible events where the probability of each event depends only on the state attained in the previous event. MCMC have a wide array of applications, the most common of…

PAT乙級1012

題目鏈接 https://pintia.cn/problem-sets/994805260223102976/problems/994805311146147840 題解 就比較簡單&#xff0c;判斷每個數字是哪種情況&#xff0c;然后進行相應的計算即可。 下面的代碼中其實數組是不必要的&#xff0c;每取一個數字就可以直接進行相應計算。 // P…

我如何在昌迪加爾大學中心組織Google Hash Code 2019

by Neeraj Negi由Neeraj Negi 我如何在昌迪加爾大學中心組織Google Hash Code 2019 (How I organized Google Hash Code 2019 at Chandigarh University Hub) This is me !!! Neeraj Negi — Google HashCode Organizer這就是我 &#xff01;&#xff01;&#xff01; Neeraj …

leetcode 665. 非遞減數列(貪心算法)

給你一個長度為 n 的整數數組&#xff0c;請你判斷在 最多 改變 1 個元素的情況下&#xff0c;該數組能否變成一個非遞減數列。 我們是這樣定義一個非遞減數列的&#xff1a; 對于數組中所有的 i (0 < i < n-2)&#xff0c;總滿足 nums[i] < nums[i 1]。 示例 1: …

django基于存儲在前端的token用戶認證

一.前提 首先是這個代碼基于前后端分離的API,我們用了django的framework模塊,幫助我們快速的編寫restful規則的接口 前端token原理: 把(token加密后的字符串,keyname)在登入后發到客戶端,以后客戶端再發請求,會攜帶過來服務端截取(token加密后的字符串,keyname),我們再利用解密…

數據分布策略_有效數據項目的三種策略

數據分布策略Many data science projects do not go into production, why is that? There is no doubt in my mind that data science is an efficient tool with impressive performances. However, a successful data project is also about effectiveness: doing the righ…

cell 各自的高度不同的時候

1, cell 根據文字、圖片等內容&#xff0c;確定自己的高度。每一個cell有自己的高度。 2&#xff0c;tableView 初始化 現實的時候&#xff0c;不是從第一個cell開始顯示&#xff0c;&#xff08;從第二個&#xff1f;&#xff09;&#xff0c;非非正常顯示。 a:cell 的高度問題…

leetcode 978. 最長湍流子數組(滑動窗口)

當 A 的子數組 A[i], A[i1], …, A[j] 滿足下列條件時&#xff0c;我們稱其為湍流子數組&#xff1a; 若 i < k < j&#xff0c;當 k 為奇數時&#xff0c; A[k] > A[k1]&#xff0c;且當 k 為偶數時&#xff0c;A[k] < A[k1]&#xff1b; 或 若 i < k < j&…

spring boot源碼下載地址

github下載&#xff1a; https://github.com/spring-projects/spring-boot/tree/1.5.x git地址&#xff1a; https://github.com/spring-projects/spring-boot.git 因為項目中目前使用的就是spring boot 1.5.19版本&#xff0c;因此這里先研究spring boot 1.5版本源碼.轉載于:h…

java基礎學習——5、HashMap實現原理

一、HashMap的數據結構 數組的特點是&#xff1a;尋址容易&#xff0c;插入和刪除困難&#xff1b;而鏈表的特點是&#xff1a;尋址困難&#xff0c;插入和刪除容易。那么我們能不能綜合兩者的特性&#xff0c;做出一種尋址容易&#xff0c;插入刪除也容易的數據結構&#xff1…

看懂nfl定理需要什么知識_NFL球隊為什么不經常通過?

看懂nfl定理需要什么知識Debunking common NFL myths in an analytical study on the true value of passing the ball在關于傳球真實價值的分析研究中揭穿NFL常見神話 Background背景 Analytics are not used enough in the NFL. In a league with an abundance of money, i…

Docker初學者指南-如何創建您的第一個Docker應用程序

您是一名開發人員&#xff0c;并且想要開始使用Docker&#xff1f; 本文是為您準備的。 (You are a developer and you want to start with Docker? This article is made for you.) After a short introduction on what Docker is and why to use it, you will be able to cr…

mybatis if-else(寫法)

mybaits 中沒有else要用chose when otherwise 代替 范例一 <!--批量插入用戶--> <insert id"insertBusinessUserList" parameterType"java.util.List">insert into business_user (id , user_type , user_login )values<foreach collection…

spring—攔截器和異常

SpringMVC的攔截器 SpringMVC攔截器-攔截器的作用 Spring MVC 的攔截器類似于 Servlet 開發中的過濾器 Filter&#xff0c;用于對處理器進行預處理和后處理。 將攔截器按一定的順序聯結成一條鏈&#xff0c;這條鏈稱為攔截器鏈&#xff08;InterceptorChain&#xff09;。在…

29/07/2010 sunrise

** .. We can only appreciate the miracle of a sunrise if we have waited in the darkness .. 人們在黑暗中等待著&#xff0c;那是期盼著如同日出般的神跡出現 .. 附&#xff1a;27/07/2010 sunrise ** --- 31 July 改動轉載于:https://www.cnblogs.com/orderedchaos/archi…