I have a confusion on handling these kind of questions.
For eg in the subsets question on Leetcode (https://leetcode.com/problems/subsets/). You can solve it using the approach which is similar to Knapsack problem and also using the general backtracking approach.
The major confusion I have is when to use which format.
Can somone help me with it?
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();
findAllsubset(nums, nums.length, list, result);
return result;
}
public void findAllsubset(int [] arr, int n, List<Integer> list, List<List<Integer>> result) {
if(n == 0){
result.add(new ArrayList<>(list));
return;
}
findAllsubset(arr, n-1, list, result);
list.add(arr[n-1]);
findAllsubset(arr, n-1, list, result);
list.remove(list.size()-1);
}
}The other way of solving is using the backtracking approach
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();
findAllsubset(nums, 0, list, result);
return result;
}
public void findAllsubset(int [] arr, int start, List<Integer> list, List<List<Integer>> result) {
result.add(new ArrayList<>(list));
for(int i=start;i<arr.length;i++) {
list.add(arr[i]);
findAllsubset(arr, i+1, list, result);
list.remove(list.size()-1);
}
}
}I usually get very much confused if I should use a for loop. It would be really helpful if someone could help me on how to approach these kind of problems.
PS - I am beginner to competitive programming. So, any guidance would be really helpful.