leetcode -- 组合问题

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

  • 所有数字(包括 target)都是正整数。
  • 解集不能包含重复的组合。 

示例 1:

输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
  [7],
  [2,2,3]
]

 采用深度优先遍历的方式解决

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        self.dfs(candidates, target, 0, [], res)
    def dfs(self, nums, target, index, path, res)
        if target < 0:
            return
        if target == 0:
            res.append(path)
            return
        for i in range(index, len(nums)):
            return self.dfs(nums, target-nums[i], i, path+[nums[i]], res)

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

说明:

  • 所有数字(包括目标数)都是正整数。
  • 解集不能包含重复的组合。 

示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
仍然使用dfs,然后要多一个判断重复的步骤
  
class Solution(object):
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        candidates.sort()
        res = []
        self.dfs(candidates, target, 0,  [], res)
        return res
    def dfs(self, nums, target, index, path, res):
        if target == 0:
            res.append(path)
            return
        if target < 0:
            return
        for i in range(index, len(nums)):
            if i > index and nums[i] == nums[i-1]:#重复的跳过
                continue
            self.dfs(nums, target-nums[i], i+1, path+[nums[i]], res)

给定一个没有重复数字的序列,返回其所有可能的全排列。

示例:

输入: [1,2,3]
输出:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
 1 class Solution(object):
 2     def permute(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: List[List[int]]
 6         """
 7         res = []
 8         self.dfs(nums, [], res)
 9         return res
10     def dfs(self, nums, path, res):
11         if not nums:
12             res.append(path)
13             return
14         for i in range(len(nums)):
15             self.dfs(nums[:i]+nums[i+1:], path+[nums[i]], res)

给定一个可包含重复数字的序列,返回所有不重复的全排列。

示例:

输入: [1,1,2]
输出:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]
 
 1 class Solution:
 2     def permuteUnique(self, nums: List[int]) -> List[List[int]]:
 3         res = []
 4         self.dfs(nums, [], res)
 5         return res
 6     def dfs(self, nums, path, res):
 7         if not nums:
 8             if path not in res:
 9                 res.append(path)
10             return
11         for i in range(len(nums)):
12             self.dfs(nums[:i]+nums[i+1:], path+[nums[i]], res)

猜你喜欢

转载自www.cnblogs.com/hengw/p/10461953.html