这一道题又是集合上面的问题,能够重复使用数字,来求得几个数之和等于目标。java
咱们能够先将大于该数字的元素去除掉,以后取出一个元素,作减法,将获得的结果再放到集合中比较,直至最后减得结果为零则成功,为负数则失败回退。所以咱们能够使用递归、堆栈、队列等来解决。spa
public class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { Arrays.sort(candidates); List<List<Integer>> result = new ArrayList<List<Integer>>(); getResult(result, new ArrayList<Integer>(), candidates, target, 0); return result; } private void getResult(List<List<Integer>> result, List<Integer> cur, int candidates[], int target, int start){ if(target > 0){ for(int i = start; i < candidates.length && target >= candidates[i]; i++){ cur.add(candidates[i]); getResult(result, cur, candidates, target - candidates[i], i); cur.remove(cur.size() - 1); }//for }//if else if(target == 0 ){ result.add(new ArrayList<Integer>(cur)); }//else if } }
遇到这种问题,首先想到递归,动态规划等方面的知识,而后不断地练习和尝试。3d