题解 | #牛群喂食#
牛群喂食
https://www.nowcoder.com/practice/591c222d73914c1ba031a660db2ef73f
知识点:回溯
思路:使用回溯实现全排列,因为这次比上一次,不需要在标记used,使用的元素,因此直接遍历即可,后续回溯一一标记判断,
如果累加的值等于我们想要的target,目标值,那么我们就存储到一个集合中
编程语言:java
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param candidates int整型一维数组
* @param target int整型
* @return int整型二维数组
*/
public int[][] cowCombinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(candidates);
backtrack(candidates, target, 0, new ArrayList<>(), result);
int[][] ans = new int[result.size()][];
for (int i = 0; i < result.size(); i++) {
ans[i] = result.get(i).stream().mapToInt(Integer::intValue).toArray();
}
return ans;
}
private void backtrack(int[] candidates, int target, int start,
List<Integer> tempList, List<List<Integer>> result) {
//终止条件
if (target < 0) {
return;
}
if (target == 0) {
result.add(new ArrayList<>(tempList));
return;
}
for (int i = start; i < candidates.length; i++) {
tempList.add(candidates[i]);
backtrack(candidates, target - candidates[i], i, tempList, result);
tempList.remove(tempList.size() - 1);
}
}
}

