Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit290e600

Browse files
committed
com
1 parent60db8b5 commit290e600

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

‎combination/CombinationSum_1203.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
packageAlgorithms.combination;
2+
3+
importjava.util.ArrayList;
4+
importjava.util.Arrays;
5+
importjava.util.List;
6+
7+
publicclassCombinationSum_1203 {
8+
publicList<List<Integer>>combinationSum(int[]candidates,inttarget) {
9+
List<List<Integer>>ret =newArrayList<List<Integer>>();
10+
if (candidates ==null ||candidates.length ==0) {
11+
returnret;
12+
}
13+
14+
// Sort to avoid duplicate solutions.
15+
Arrays.sort(candidates);
16+
17+
dfs(candidates,target,newArrayList<Integer>(),ret,0);
18+
returnret;
19+
}
20+
21+
publicvoiddfs(int[]candidates,inttarget,List<Integer>path,List<List<Integer>>ret,intindex) {
22+
if (target <0) {
23+
return;
24+
}
25+
26+
if (target ==0) {
27+
ret.add(newArrayList(path));
28+
return;
29+
}
30+
31+
// i 的起始值是跟排列的最主要区别。因为与顺序无关,所以我们必须只能是升序,也就是说下一个取值只能是i本身
32+
// 或是i的下一个。
33+
// 但是排列的话,可以再取前同的。1, 2 与2 1是不同的排列,但是同一个组合
34+
for (inti =index;i <candidates.length;i++) {
35+
intnum =candidates[i];
36+
path.add(num);
37+
38+
// 注意,最后的参数是i,不是index!!
39+
dfs(candidates,target -num,path,ret,i);
40+
path.remove(path.size() -1);
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp