算法39. Combination Sum

39. Combination Sum
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

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

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

给一些没有重复的候选数字和一个目标值,在候选数字中找到和为目标值的所有唯一组合。
可以重复使用候选数字。
注意:

  • 所有的数字都是正整数
  • 不要包含重复解
class Solution {
    public List> combinationSum(int[] candidates, int target) {
        
    }
}

解:
虽然给的例子是有序的,但是题目并没有说候选数字是有序的。那么先正序排序,从头开始遍历,用目标值减去当前位置值,如果大于0,则递归从头遍历;如果等于0,说明找到一种解;小于0,说明不行。然后i++,直到当前值都比目标大。以下为代码:

public List> combinationSum(int[] candidates, int target) {
    Arrays.sort(candidates);
    List> result = new ArrayList>();
    getResult(result, new ArrayList(), candidates, target, 0);
    
    return result;
}

private void getResult(List> result, List 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);
        }
    } else if(target == 0 ){// 找到一种解
        result.add(new ArrayList(cur));
    }
}

你可能感兴趣的:(算法39. Combination Sum)