Created
April 2, 2020 14:52
-
-
Save chaudharisuresh997/b7c229702dfba2442b1312448dfcebc2 to your computer and use it in GitHub Desktop.
Combination sum-Sort list of list nested list https://www.interviewbit.com/problems/combination-sum/
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
//https://www.interviewbit.com/problems/combination-sum/ | |
public class Solution { | |
public ArrayList<ArrayList<Integer>> combinationSum(ArrayList<Integer> A, int B) { | |
ArrayList<ArrayList<Integer>> big=new ArrayList<ArrayList<Integer>>(); | |
if(A.size()==0){ | |
return big; | |
} | |
Collections.sort(A); | |
combination(big,0,A,B,new ArrayList<Integer>(),B); | |
Collections.sort(big,new Comparator<ArrayList<Integer>>(){ | |
@Override | |
public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) { | |
for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) { | |
int c = o1.get(i).compareTo(o2.get(i)); | |
if (c != 0) { | |
return c; | |
} | |
} | |
return Integer.compare(o1.size(), o2.size()); | |
} | |
}); | |
return big; | |
} | |
public void combination(ArrayList<ArrayList<Integer>> big,int start,ArrayList<Integer> A,int B,ArrayList<Integer> small,int sum){ | |
if(sum<0){ | |
return; | |
} | |
else if(sum==0){ | |
ArrayList<Integer> cloneLs=new ArrayList<Integer>(small); | |
Collections.sort(cloneLs); | |
if(!big.contains(cloneLs)){ | |
big.add(cloneLs); | |
} | |
} | |
else{ | |
for(int i=start;i<A.size();i++){ | |
small.add(A.get(i)); | |
combination(big,start+1,A,B,small,sum-A.get(i)); | |
combination(big,start,A,B,small,sum-A.get(i)); | |
//} | |
if(small.size()>0){ | |
//sum-=small.get(small.size()-1); | |
small.remove(small.size()-1); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment