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

Commit47eea51

Browse files
use backtracking to solve Subsets I & II
1 parentf2c3511 commit47eea51

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

‎MEDIUM/src/medium/Subsets.java

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,9 @@
88
publicclassSubsets {
99

1010
publicstaticvoidmain(String...strings){
11-
int[]nums =newint[]{1,2,3};
12-
List<List<Integer>>result =subsets(nums);
11+
// int[] nums = new int[]{1,2,3};
12+
int[]nums =newint[]{1,2,2};
13+
List<List<Integer>>result =subsets_backtracking(nums);
1314
CommonUtils.printIntegerList(result);
1415
}
1516

@@ -29,5 +30,23 @@ public static List<List<Integer>> subsets(int[] nums) {
2930
}
3031
returnresult;
3132
}
33+
34+
/**this post: https://discuss.leetcode.com/topic/46159/a-general-approach-to-backtracking-questions-in-java-subsets-permutations-combination-sum-palindrome-partitioning
35+
* is really cool!*/
36+
publicstaticList<List<Integer>>subsets_backtracking(int[]nums) {
37+
List<List<Integer>>result =newArrayList();
38+
backtracking(result,newArrayList<>(),nums,0);
39+
returnresult;
40+
}
3241

42+
privatestaticvoidbacktracking(List<List<Integer>>result,List<Integer>temp,int[]nums,intstart) {
43+
//ATTN: you'll have to make a new list here before entering the for loop
44+
result.add(newArrayList(temp));
45+
for(inti =start;i <nums.length;i++){
46+
if(i !=start &&nums[i] ==nums[i-1])continue;//add this line here to skip duplicates for Subsets II
47+
temp.add(nums[i]);
48+
backtracking(result,temp,nums,i+1);
49+
temp.remove(temp.size()-1);
50+
}
51+
}
3352
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp