Skip to content

Commit f415e9c

Browse files
author
王俊超
committed
commit
1 parent 74c7d61 commit f415e9c

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

.idea/modules.xml

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.LinkedList;
4+
import java.util.List;
5+
6+
/**
7+
* @author: wangjunchao(王俊超)
8+
* @time: 2018-09-28 15:11
9+
**/
10+
public class Solution {
11+
public List<List<Integer>> combinationSum(int[] nums, int target) {
12+
// 用于保存结果
13+
List<List<Integer>> list = new LinkedList<>();
14+
Arrays.sort(nums);
15+
backtrack(list, new ArrayList<>(), nums, target, 0);
16+
return list;
17+
}
18+
19+
// 回溯法
20+
// list:保存总的结果
21+
// tempList:保存临时结果
22+
// nums:输入的数组
23+
// remain:剩下的值
24+
// start:可用的值在数组中的起始位置
25+
private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, int remain, int start){
26+
// 不够减
27+
if(remain < 0) {
28+
return;
29+
} else if(remain == 0) { // 刚好够减
30+
list.add(new LinkedList<>(tempList));
31+
} else {
32+
// 从剩下的数中一个一个尝试
33+
for(int i = start; i < nums.length; i++){
34+
// 假设这个值是临时结果中的一个值
35+
tempList.add(nums[i]);
36+
// 处理下一步
37+
backtrack(list, tempList, nums, remain - nums[i], i);
38+
// 现场还原
39+
tempList.remove(tempList.size() - 1);
40+
}
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)