Combination Sum

来源:互联网 发布:mac app如何打包成dmg 编辑:程序博客网 时间:2024/06/05 21:05

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 (a1a2, … , 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] 

Show Tags

Have you met this question in a real interview?

思路:DFS+backtracking;

穷举法+剪枝法。

注意:

1. candidates 要sort

2. 因为元素可以重复,这里要注意两点。

    2.1 candidates里面有重复的元素,后面一个可以去掉,因为前面计算的时候,可以取自己。like [2,2,3] 计算第二个2的时候可以忽略。

    2.2 还是像combination里面一样,start point来决定下一个取值是从哪里开始的,因为可以重复,所以,这里下层循环可以从自身开始。combination的下一层是从i+1开始,这题是从i开始。

public class Solution {     public List<List<Integer>> combinationSum(int[] candidates, int target) {         List<List<Integer>> lists = new ArrayList<List<Integer>>();         if(candidates == null || candidates.length == 0){             return lists;         }         List<Integer> list = new ArrayList<Integer>();         Arrays.sort(candidates);         collect(candidates, lists, list, target, 0 , 0);         return lists;     }          public void collect(int[] candidates, List<List<Integer>> lists, List<Integer> list, int target, int sum, int index){         if(sum > target) return;         if(sum == target){             lists.add(new ArrayList<Integer>(list));             return;         }         for(int i=index; i<candidates.length; i++){             if(i>index && candidates[i] == candidates[i-1]){                 continue;             }             sum += candidates[i];             list.add(candidates[i]);             collect(candidates, lists, list, target, sum, i);             list.remove(list.size()-1);             sum -= candidates[i];         }     } }


0 0