LeetCode 組合總和

2021-09-02 19:35:26 字數 1706 閱讀 6625

給定乙個由正整數組成且不存在重複數字的陣列,找出和為給定目標正整數的組合的個數。

示例:

nums = [1, 2, 3]

target = 4

所有可能的組合為:

(1, 1, 1, 1)

(1, 1, 2)

(1, 2, 1)

(1, 3)

(2, 1, 1)

(2, 2)

(3, 1)

請注意,順序不同的序列被視作不同的組合。

因此輸出為 7。

高階:

如果給定的陣列中含有負數會怎麼樣?

問題會產生什麼變化?

我們需要在題目中新增什麼限制來允許負數的出現?

思考:

首先考慮遞迴關係。怎樣的組合的target與那些比小的數的組合的target

所以我們知道這target是陣列中數字的總和。想象一下,我們只需要乙個數字來達到目標​​,這個數字可以是陣列中的任何乙個,對嗎?所以#的組合targetcomb[target] = sum(comb[target - nums[i]]), where 0 <= i < nums.length, and target >= nums[i]

在給出的示例中,我們實際上可以找到4個組合的#與3(4 - 1),2(4 - 2)和1(4 - 3)的組合。結果,comb[4] = comb[4-1] + comb[4-2] + comb[4-3] = comb[3] + comb[2] + comb[1]

然後考慮基本情況。因為如果目標是0,只有一種方法可以獲得零,即使用0,我們可以設定comb[0] = 1

現在我們可以提出至少乙個遞迴解決方案。

public int combinationsum4(int nums, int target) 

int res = 0;

for (int i = 0; i < nums.length; i++)

}return res;

}

現在對於dp解決方案,我們只需要找出儲存中間結果的方法,以避免多次計算相同的組合和。我們可以使用陣列來儲存這些結果,並在計算之前檢查是否已有結果。我們可以用-1填充陣列以指示結果尚未計算。0不是乙個好的選擇,因為它意味著目標沒有組合總和。

private int dp;

public int combinationsum4(int nums, int target)

private int helper(int nums, int target)

int res = 0;

for (int i = 0; i < nums.length; i++)

}dp[target] = res;

return res;

}

public int combinationsum4(int nums, int target) }}

return comb[target];

}

LeetCode組合總和

39.給定乙個無重複元素的陣列 candidates 和乙個目標數 target 找出 candidates 中所有可以使數字和為 target 的組合。candidates 中的數字可以無限制重複被選取。說明 所有數字 包括 target 都是正整數。解集不能包含重複的組合。解法 static l...

LeetCode 組合總和

部落格說明 介紹39.組合總和 題目給定乙個無重複元素的陣列 candidates 和乙個目標數 target 找出 candidates 中所有可以使數字和為 target 的組合。candidates 中的數字可以無限制重複被選取。說明 所有數字 包括 target 都是正整數。解集不能包含重複...

leetcode組合總和IV

1.動態規劃 設dp target dp i 表示target i時的組合個數 遍歷target,對於中間元素i,遍歷nums陣列,如果i nums j target 則dp i nums j dp i nums j dp i 即當target等於i nums j 時,新增的組合數為dp i 即dp...