39. Combination Sum

一、题目

  1、审题

  2、分析:

    给出一个不重复的数字数组,一个目标数字target,求数组中的元素组合所得的和为 target 的所有组合,其中数组中的元素可以多次使用。

 

二、解答

  1、思路:

    利用递归算法求得所有组合。

  

public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> targetList = new LinkedList<List<Integer>>();
        Arrays.sort(candidates);

        getResult(targetList, new ArrayList<Integer>(), candidates, target, 0);
        return targetList;
    }
    
    public void getResult(List<List<Integer>> targetList, 
            ArrayList<Integer> curreyList, int[] candidates, int target, int start) { // target > 0 if(target > 0) { for(int i = start; i < candidates.length && target >=candidates[i]; i++) { curreyList.add(candidates[i]); getResult(targetList, curreyList, candidates, target-candidates[i], i); curreyList.remove(curreyList.size()-1); } } // 合适 else if(target == 0) { targetList.add(new ArrayList<Integer>(curreyList));         // add(new ArrayList<Integer>(resultList) : 复制 resultList 的值 // add((resultList)): 添加 resultList 指针,其中的 resultList 的值会变化 } } }

 

posted @ 2018-09-03 20:46  skillking2  阅读(91)  评论(0编辑  收藏  举报