乘风破浪:LeetCode真题_039_Combination Sum

时间:2023-03-09 16:15:50
乘风破浪:LeetCode真题_039_Combination Sum

乘风破浪:LeetCode真题_039_Combination Sum

一、前言

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

二、Combination Sum

2.1 问题

乘风破浪:LeetCode真题_039_Combination Sum

乘风破浪:LeetCode真题_039_Combination Sum

2.2 分析与解决

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

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

乘风破浪:LeetCode真题_039_Combination Sum

三、总结

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