for an input of n=3 and k=7 why is the combination [1,2,3] being added despite its sum being 6 and not 7.
I am running a loop from 1 to 9, and then adding numbers and i have avoided duplicates and also combinations that are permutations of each other by sorting and adding to a set
<code>class Solution {
public void find(List<Integer> ds,int k,int n){
if(k==0){
if(n==0){
Collections.sort(ds);
ans.add(new ArrayList<>(ds));
}
return;
}
for(int i=1;i<10;i++){
if(ds.contains(i))continue;
ds.add(i);
find(ds,k-1,n-i);
ds.remove(ds.size()-1);
}
}
</code>
<code>class Solution {
public void find(List<Integer> ds,int k,int n){
if(k==0){
if(n==0){
Collections.sort(ds);
ans.add(new ArrayList<>(ds));
}
return;
}
for(int i=1;i<10;i++){
if(ds.contains(i))continue;
ds.add(i);
find(ds,k-1,n-i);
ds.remove(ds.size()-1);
}
}
</code>
class Solution {
public void find(List<Integer> ds,int k,int n){
if(k==0){
if(n==0){
Collections.sort(ds);
ans.add(new ArrayList<>(ds));
}
return;
}
for(int i=1;i<10;i++){
if(ds.contains(i))continue;
ds.add(i);
find(ds,k-1,n-i);
ds.remove(ds.size()-1);
}
}
New contributor
Hitha Shetty is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.