我有兩個整數陣列。我正在尋找一種演算法來平衡兩個陣列上的兩個陣列的數量之和(盡可能準確)。
數字應該以這樣一種方式分布在陣列之間,即存在平衡并且兩個陣列具有相同的數字總和。如果無法分配,則應輸出差異。
最后,兩個陣列中的數值應該相同(不是整數的數量)。在所示的情況下,解決方案很簡單,因為只需要移動一個數字。但是,也有一些復雜的情況,即必須在“兩個方向”上移動數字才能達到平衡。

這里最好的解決方案是什么?
提前謝謝了。
uj5u.com熱心網友回復:
- 只需創建一個陣列并在其中填充兩個陣列值。
- 使用磁區相等子集總和。
解決方案-1:(如果您只想檢查是否可能,請使用它)
def canPartition(self, nums: List[int]) -> bool:
total = sum(nums)
if(total%2 == 1):
return False
size = len(nums)
amount= total//2
m = 1
for n in nums:
m |= (m << n)
return (m >> amount) & 1
解決方案-2:(如果你想要陣列值只需更新下面代碼的邏輯)
def canPartition(self, nums: List[int]) -> bool:
total = sum(nums)
if(total%2 == 1):
return False
size = len(nums)
amount= total//2
total = [False for i in range(amount 1)]
total[0] = True
for j in nums:
for i in range(amount,j-1,-1):
if(i-j >=0):
if(total[i-j]):
total[i] = True
if(total[amount] == False):
return False
else:
return total[amount]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/341189.html
