乘风破浪:LeetCode真题_039_Combination Sum

乘风破浪:LeetCode真题_039_Combination Sum

1、前言

    这一道题又是集合上面的问题,能够重复使用数字,来求得几个数之和等于目标。java

2、Combination Sum

2.1 问题

2.2 分析与解决

    咱们能够先将大于该数字的元素去除掉,以后取出一个元素,作减法,将获得的结果再放到集合中比较,直至最后减得结果为零则成功,为负数则失败回退。所以咱们能够使用递归、堆栈、队列等来解决。spa

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

3、总结

    遇到这种问题,首先想到递归,动态规划等方面的知识,而后不断地练习和尝试。3d

相关文章
相关标签/搜索