1

题目要求

Given a set of candidate numbers (C) (without duplicates) 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.
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]
]

一个整数数组,数组中的值不重复,要求在数组中找到所有的子数组,子数组满足元素的和为目标值的条件

思路和代码

这道题目有一个标签是backtracking,即在前一种条件的情况下计算当前条件产生的结果值。在这道题中,我结合了递归的思想来。就是将当前的值作为一个潜在的结果值加入一个结果数组将数组作为当前结果传入下一轮递归。

public class CombinationSum_39 {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        
        for(int i = 0 ; i<candidates.length ; i++){
            if(candidates[i] == target){
                result.add(Arrays.asList(candidates[i]));
            }else{ 
                List<Integer> temp = new ArrayList<Integer>();
                temp.add(candidates[i]);
                combinationSum(candidates, i, target-candidates[i], temp);

            }
        }
        return result;
    }
    
    public void combinationSum(int[] candidates, int start, int target, List<Integer> currentResult){
        for(int i = start ; i < candidates.length ; i++){
            if(candidates[i] == target){
                currentResult.add(candidates[i]);
                result.add(currentResult);
                return;
            }
            if(candidates[i] > target){
                return;
            }
            if(candidates[i] < target){
                List<Integer> temp = new ArrayList<Integer>();
                temp.addAll(currentResult);
                temp.add(candidates[i]);
                combinationSum(candidates, i, target-candidates[i], temp);
            }
        }
    }
}

clipboard.png
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~


raledong
2.7k 声望2k 粉丝

心怀远方,负重前行