Leetcode: Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.



The same repeated number may be chosen from C unlimited number of times.



Note:

All numbers (including target) will be positive integers.

Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).

The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7, 

A solution set is: 

[7] 

[2, 2, 3] 

典型的recursion方法,找符合要求的path,存入result的ArrayList中。所以方法还是建立一个ArrayList<ArrayList<Integer>> result, 建立一个ArrayList<Integer> path,用recursion当找到符合条件的path时,存入result中。

我在做这道题时遇到了一个问题:添加 path 进入 result 中时,需要这样res.add(new ArrayList<Integer>(path)); 如果直接res.add(path); 会出错

比如我遇到的错误是:Input:[1], 1    Output:[[]]     Expected:[[1]],没能够把path: [1] 添加到res里面去,没有成功。(具体我现在也不知道为什么)

第二遍做法:17行可以注释掉,Candidate不会存在重复元素

 1 public class Solution {

 2     public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {

 3         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();

 4         ArrayList<Integer> item = new ArrayList<Integer>();

 5         Arrays.sort(candidates);

 6         helper(res, item, candidates, target, 0);

 7         return res;

 8     }

 9     

10     public void helper(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> item, int[] candidates, int remain, int start) {

11         if (remain < 0) return;

12         if (remain == 0) {

13             res.add(new ArrayList<Integer>(item));

14             return;

15         }

16         for (int i=start; i<candidates.length; i++) {

17             //if (i>start && candidates[i] == candidates[i-1]) continue;

18             item.add(candidates[i]);

19             helper(res, item, candidates, remain-candidates[i], i);

20             item.remove(item.size()-1);

21         }

22     }

23 }

 

 

你可能感兴趣的:(LeetCode)