-
Notifications
You must be signed in to change notification settings - Fork 40
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #31 from raginiisingh/Combination_sum_leetcode
Q39, Combination Sum using Java
- Loading branch information
Showing
1 changed file
with
24 additions
and
0 deletions.
There are no files selected for viewing
24 changes: 24 additions & 0 deletions
24
leetCode Solutions/Q39_CombinationSum/Q39_CombinationSum.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |