๐ 40. ็ปๅๆปๅ II
2022ๅนด6ๆ9ๆฅ
- algorithm
๐ 40. ็ปๅๆปๅ II
้พๅบฆ: ๐
้ฎ้ขๆ่ฟฐ
่งฃๆณ
class Solution {
List<List<Integer>> res = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
// ๆ่ทฏ๏ผ
// ๅฏ้ๅคๆฐ็ป + ๆ ้ๅค้ๅ
Arrays.sort(candidates);
int len = candidates.length;
LinkedList<Integer> path = new LinkedList<>();
mySol(candidates, target, len, 0, 0, path);
return res;
}
private void mySol(int[] candidates, int target, int len, int index, int sum, LinkedList<Integer> path) {
// ้ๅฝ็ปๆญขๆกไปถ
if(sum > target) {
return;
}
if(sum == target) {
res.add(new LinkedList<>(path));
return;
}
if(index > len) {
return;
}
for(int i = index; i < len; i ++) {
if(sum + candidates[i] > target) {
return;
}
// ๅฝๅๆ่ฅๅไธไธชๅ
็ด ๅทฒ็ป่ขซ้ๅ๏ผๅๅฝๅๆไธๅญๅจ
if(i > index && candidates[i] == candidates[i - 1]) {
continue;
}
path.addLast(candidates[i]);
mySol(candidates, target, len, i + 1, sum + candidates[i], path);
path.removeLast();
}
}
}