Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Q39, Combination Sum using Java #31

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions leetCode Solutions/Q39_CombinationSum/Q39_CombinationSum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/* This solution uses the concept of recursion by considering both the cases of idea of picking or not picking an element in the array to find the target sum */

class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
findCombination(0,candidates,result, new ArrayList<>(), target);
return result;
}
public void findCombination(int i, int arr[],List<List<Integer>> result, ArrayList<Integer> al,int target) {
if(i== arr.length){
if(target == 0) result.add(new ArrayList<>(al));
return;
}
if(arr[i]<=target){
//pick single element multiple times
al.add(arr[i]);
//we are not changing index i, because we are picking same element multiple times
findCombination(i,arr,result,al, target-arr[i]);
al.remove(al.size()-1);
}
//moving to next index and start again with pick/not-pick principle
findCombination(i+1,arr,result, al, target);
}
}