'What wrong with my solution to combination sum problem
why is my code not working for inputs [2,3,5],Target =8. Have debugged this so many times but cant understand y at some point sum becomes 3 while the only element in the list is equal to 2. https://leetcode.com/problems/combination-sum/
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
combine(candidates,target,new ArrayList<Integer>(),ans,0);
return ans;
}
public void combine(int[] candidates, int target,List<Integer> curr, List<List<Integer>> ans,int sum)
{
if(sum>target)
return;
if(sum==target)
{
if(!isexists(curr,ans))
{
List<Integer> temp = new ArrayList<>(curr);
Collections.sort(temp);
ans.add(temp);
}
return;
}
for(int c :candidates)
{
curr.add(c);
sum=sum+c;
combine(candidates,target,curr,ans,sum);
curr.remove(curr.size()-1);
sum=sum-c;
}
}
public boolean isexists(List<Integer> curr, List<List<Integer>> ans)
{
Collections.sort(curr);
for(List<Integer> l:ans)
{
if(l.equals(curr))
return true;
}
return false;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
