zoukankan      html  css  js  c++  java
  • leetcode-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]
    ]

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

    这道题就是一个回溯的思路。

    可以看https://leetcode-cn.com/problems/combination-sum/solution/hui-su-suan-fa-jian-zhi-python-dai-ma-java-dai-m-2/

    public class Solution {
        private List<List<Integer>> res = new ArrayList<>();
        private int[] candidate;
        private int len;
    
        private List<List<Integer>> combinationSum(int[] candidate, int target) {
            int len = candidate.length;
            if (len == 0) {
                return res;
            }
            Arrays.sort(candidate);
            this.len = len;
            this.candidate = candidate;
            findCombinationSum(target, 0, new Stack<Integer>());
            return res;
        }
    
        private void findCombinationSum(int residue, int start, Stack<Integer> pre) {
            if (residue == 0) {
                res.add(new ArrayList<Integer>(pre));
                return;
            }
            for (int i = start; i < len && residue - candidate[i] >= 0; i++) {
                pre.push(candidate[i]);
                findCombinationSum(residue - candidate[i], i, pre);
                pre.pop();
            }
        }
    
        public static void main(String[] args) {
            int[] candidates = {3, 4, 6, 7};
            int target = 7;
            Solution solution = new Solution();
            List<List<Integer>> combinationSum = solution.combinationSum(candidates, target);
            System.out.println(combinationSum);
    
        }
    }

    end

    一个没有高级趣味的人。 email:hushui502@gmail.com
  • 相关阅读:
    今日头条、Face++开发岗面经
    美团offer面经
    成都百度测试开发一二面面经
    美团四面面经
    久邦数码(3G门户)面试
    58 面试
    好未来提前批
    百度提前批
    新浪面经
    Java Programs
  • 原文地址:https://www.cnblogs.com/CherryTab/p/12208263.html
Copyright © 2011-2022 走看看