zoukankan      html  css  js  c++  java
  • 39. 组合总和

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

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

    说明:

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

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

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

    提示:

    1 <= candidates.length <= 30
    1 <= candidates[i] <= 200
    candidate 中的每个元素都是独一无二的。
    1 <= target <= 500

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/combination-sum
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    class Solution:
        def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
            size=len(candidates)
            if size<=0:
                return []
            candidates.sort()
    
            path=[]
            res=[]
            self._find_path(target,path,res,candidates,0,size)
    
            return res
    
        def _find_path(self,target,path,res,candidates,begin,size):
            if target==0:
                res.append(path.copy())
            else:
                for i in range(begin,size):
                    left=target-candidates[i]
                    if left<0:
                        break
                    path.append(candidates[i])
                    self._find_path(left,path,res,candidates,i,size)
                    path.pop()
    class Solution {
        public List<List<Integer>> combinationSum(int[] nums, int target) {
            List<List<Integer>> list = new ArrayList<>();
            Arrays.sort(nums);
            backtrack(list, new ArrayList<>(), nums, target, 0);
            return list;
        }
    
        private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, int remain, int start){
            if(remain < 0) return;
            else if(remain == 0) list.add(new ArrayList<>(tempList));
            else{ 
                for(int i = start; i < nums.length; i++){
                    tempList.add(nums[i]);
                    backtrack(list, tempList, nums, remain - nums[i], i); // 不用i + 1 因为可以重复使用数字
                    tempList.remove(tempList.size() - 1);
                }
            }
        }
    }
  • 相关阅读:
    LeetCode "Median of Two Sorted Arrays"
    LeetCode "Distinct Subsequences"
    LeetCode "Permutation Sequence"

    LeetCode "Linked List Cycle II"
    LeetCode "Best Time to Buy and Sell Stock III"
    LeetCode "4Sum"
    LeetCode "3Sum closest"
    LeetCode "3Sum"
    LeetCode "Container With Most Water"
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13843278.html
Copyright © 2011-2022 走看看