Java [Leetcode 39]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]

解题思路:

首先将数组排序,然后应用回溯和贪心的算法,首先从最小的数开始,尽可能的将该数字放入List中,如果加入的数目太多导致下面没有数字可以使综合等于target则将之前加入的数字弹出,换进下一个数字,如此反复。

代码如下:

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;
	}

	public void getResult(List<List<Integer>> result,
			List<Integer> current, int[] candiates, int target, int start) {
		if (target > 0) {
			for (int i = start; i < candiates.length && target >= candiates[i]; i++) {
				current.add(candiates[i]);
				getResult(result, current, candiates, target - candiates[i], i);
				current.remove(current.size() - 1);
			}
		} else if (target == 0) {
			result.add(new ArrayList<Integer>(current));
		}
	}
}

  

原文地址:https://www.cnblogs.com/zihaowang/p/5020537.html