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

Commitd9759fa

Browse files
author
applewjg
committed
CombinationSum
Change-Id: Iec3a3b218ec60ba68dbc07bf18709c2e77d06266
1 parent299a8b8 commitd9759fa

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

‎CombinationSumII.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 20, 2014
4+
Problem: Combination Sum II
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/combination-sum-ii/
7+
Notes:
8+
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations
9+
in C where the candidate numbers sums to T.
10+
Each number in C may only be used once in the combination.
11+
Note:
12+
All numbers (including target) will be positive integers.
13+
Elements in a combination (a1, a2, .. , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak).
14+
The solution set must not contain duplicate combinations.
15+
For example, given candidate set 10,1,2,7,6,1,5 and target 8,
16+
A solution set is:
17+
[1, 7]
18+
[1, 2, 5]
19+
[2, 6]
20+
[1, 1, 6]
21+
22+
Solution: ..Similar to Combination Sum I, except for line 42 && 44.
23+
*/
24+
publicclassSolution {
25+
publicList<List<Integer>>combinationSum2(int[]num,inttarget) {
26+
List<List<Integer>>res =newArrayList<List<Integer>>();
27+
Arrays.sort(num);
28+
ArrayList<Integer>path =newArrayList<Integer>();
29+
combinationSumRe(num,target,0,path,res);
30+
returnres;
31+
}
32+
voidcombinationSumRe(int[]candidates,inttarget,intstart,ArrayList<Integer>path,List<List<Integer>>res) {
33+
if (target ==0) {
34+
ArrayList<Integer>p =newArrayList<Integer>(path);
35+
res.add(p);
36+
return;
37+
}
38+
for (inti =start;i <candidates.length &&target >=candidates[i]; ++i) {
39+
if (i!=start &&candidates[i-1] ==candidates[i])continue;
40+
path.add(candidates[i]);
41+
combinationSumRe(candidates,target-candidates[i],i+1,path,res);
42+
path.remove(path.size() -1);
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp