1. 程式人生 > >【LeetCode每天一題】Combination Sum II(組合和II)

【LeetCode每天一題】Combination Sum II(組合和II)

turn mic and microsoft str find get break .so

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.Each number in candidates may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates =[10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]
思路

   這道題的思路和前一道組合數的思路都是類似的,只不過在細節處理上不同。詳細思路見代碼
解決代碼

 1 class Solution(object):
 2     def combinationSum2(self, nums, target):
 3         """
 4         :type candidates: List[int]
 5         :type target: int
 6         :rtype: List[List[int]]
 7         """
 8         if len(nums) < 1:    # nums為空直接返回
9 return [] 10 nums.sort() # 對nums進行排序,主要目的是為了較少遞歸次數。 11 res =[] 12 self.get_res(nums, target, [], res) # 遞歸 13 return res 14 15 def get_res(self, nums, target, path, res): 16 if target == 0: # 結束條件,找到滿足的組合將其添加進res列表中 17 res.append(path) 18 return 19 if target < 0: # 沒有滿足的組合直接返回 20 return 21 for i in range(len(nums)): # 從第下標0開始尋找 22 if i > 0 and nums[i] == nums[i-1]: # 如果當前下小標元素和前一個相等直接跳過,避免產生相同的組合。 23 continue 24 if nums[i] > target: # 當前下標直接大於target,後面的元素都不會滿足直接返回。 25 break 26 self.get_res(nums[i+1:], target-nums[i], path+[nums[i]], res) # 下一次遞歸時,都將nums大小減一。意味著從下一個開始重新尋找滿足條件的組合 27

【LeetCode每天一題】Combination Sum II(組合和II)