Skip to content

Commit

Permalink
Merge pull request #362 from avnisinngh/Second_Add
Browse files Browse the repository at this point in the history
Adding LeetCode Solutions
  • Loading branch information
PRIYESHSINGH24 authored Jan 20, 2025
2 parents a9d6507 + cb2b7f1 commit a482fd2
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
28 changes: 28 additions & 0 deletions LeetCode/39. Combination Sum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import java.util.ArrayList;
import java.util.List;

class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> ds = new ArrayList<>();
combination(candidates, target, 0, ans, ds);
return ans;
}
public void combination(int[] candidates, int target, int index, List<List<Integer>> ans, List<Integer> ds) {
//base case
if(index == candidates.length) {
if(target == 0) {
ans.add(new ArrayList<>(ds));
}
return ;
}
//pick
if(candidates[index] <= target) {
ds.add(candidates[index]);
combination(candidates, target - candidates[index], index, ans,ds);
ds.remove(ds.size()-1);
}
//not pick
combination(candidates, target, index+1, ans,ds);
}
}
31 changes: 31 additions & 0 deletions LeetCode/40. Combination Sum II.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> ds = new ArrayList<>();
Arrays.sort(candidates);
combination(candidates, target, ans, ds, 0);
return ans;
}
public void combination(int[] candidates, int target, List<List<Integer>> ans, List<Integer> ds, int index) {
//base case
if(target == 0) {
ans.add(new ArrayList<>(ds));
return ;
}
for(int i = index ; i < candidates.length; i++) {

//not pick
if(i > index && candidates[i] == candidates[i-1]) continue;
if(candidates[i] > target) break;

//pick
ds.add(candidates[i]);
combination(candidates, target - candidates[i], ans, ds, i + 1);
ds.remove(ds.size() - 1);
}
}
}

0 comments on commit a482fd2

Please sign in to comment.