Skip to content

Instantly share code, notes, and snippets.

@Chen-tao
Created January 30, 2017 04:52
Show Gist options
  • Save Chen-tao/466114c4174c8a71394b31d88675de82 to your computer and use it in GitHub Desktop.
Save Chen-tao/466114c4174c8a71394b31d88675de82 to your computer and use it in GitHub Desktop.
//https://leetcode.com/problems/combination-sum/
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (candidates == null || candidates.length == 0)
return result;
ArrayList<Integer> current = new ArrayList<Integer>();
Arrays.sort(candidates);
/**
* depth-first search(DFS).
* To solve DFS problem, recursion is a normal implementation.
* Note that the candidates array is not sorted, we need to sort it
* first.
*/
combinationSum(candidates, target, 0, current, result);
return result;
}
/**
*
* @param candidates 候选元素
* @param target 目标和
* @param j index
* @param curr 当前集合
* @param result 结果集合
*/
public void combinationSum(int[] candidates, int target, int j, ArrayList<Integer> curr, List<List<Integer>> result) {
if (target == 0) {
ArrayList<Integer> temp = new ArrayList<Integer>(curr);
result.add(temp);
return;
}
for (int i = j; i < candidates.length; i++) {
if (target < candidates[i])
return;
curr.add(candidates[i]);
combinationSum(candidates, target - candidates[i], i, curr, result);
curr.remove(curr.size() - 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment