Basic Code Snippet for "Backtracking" concept in java.
353
May 10, 2022
Problem statement -
- Given array of distinct elements and target.
- Task is to find all the unique combinations of elements of array where the chose numbers sum is equal to target.
- You can choose a number from array multiple no of times.
Example - array -> [2,3,5] , target -> 8
output - [ [2,2,2,2] , [2,3,3] , [3,5] ]
We can apply backtracking concept here-
3 simple steps to remember for "Backtracking" type of problems-
Steps 1 : Do some changes( eg - add an element into list, placing a queen on a chess board position etc etc)
Step 2 : Iterate over all possibilites(eg - place the next queen on chess board, and then next and so on )
Step 3 : Undo the changes done in first step (eg - Backtrack if no possiblity for placing the next queen )
class Solution {
List<List<Integer>> res=new ArrayList<>(); // for storing all unique combinations
public void getCombinationsSum(int [] arr, List<Integer> currList, int index, int target){
if(target==0){
// get one unique combination , now storing it in res
res.add(new ArrayList<>(currList));
}else{
for(int i=index;i<arr.length;i++){
// if element is greater than target move to next element of array
if(target-arr[i] < 0) continue;
// Step 1 mentioned above
currList.add(arr[i]);
// Step 2
getCombinationsSum(arr, currList, i, target-arr[i]);
// Step 3
currList.remove(currList.size()-1);
}
}
}
public List<List<Integer>> combinationSum(int[] arr, int target) {
int len=arr.length;
if(len>0){
List<Integer> currList=new ArrayList<>();
// initial call to start recursion/ backtracking
getCombinationsSum(arr,currList,0,target);
}
return res;
}}
Comments (0)

