Leetcode Combination Sum 分析

来源:互联网 发布:wordpress 百万数据 编辑:程序博客网 时间:2024/05/30 23:02

题目地址: https://oj.leetcode.com/problems/combination-sum/


public class Solution {    public List<List<Integer>> combinationSum(int[] candidates, int target) {                // Create return list        List<List<Integer>> res = new ArrayList<List<Integer>>();                // Null prevention        if (candidates == null || candidates.length == 0)   return res;                // Sort the candidates        Arrays.sort(candidates);                // Choose from the candidates to increase the list        helper(candidates, 0, target, new ArrayList<Integer>(), res);                return res;    }            private void helper(int[] candidates, int start, int target, ArrayList<Integer> item, List<List<Integer>> res) {                // if list of item is bigger then target        if (target < 0) return;                // if match        if (target == 0) {            // item needed for later            res.add(new ArrayList<Integer>(item));            return;        }                // Backtracking        for (int i = start; i < candidates.length; i++) {            // Skip the same number            if (i > 0 && candidates[i] == candidates[i-1])  continue;                        // add the candidate to the list            item.add(candidates[i]);            helper(candidates, i, target - candidates[i], item, res);                        // Delete the last added number, for we don't know if it's gonna work or not            item.remove(item.size() - 1);        }    }}


0 0
原创粉丝点击