Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created June 3, 2015 20:17
Show Gist options
  • Save cangoal/0d996118d3b7922bc5fe to your computer and use it in GitHub Desktop.
Save cangoal/0d996118d3b7922bc5fe to your computer and use it in GitHub Desktop.
LeetCode - Combinations
public ArrayList<ArrayList<Integer>> combine(int n, int k) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
if(n <= 0 || k <= 0 || n < k) return ret;
helper(ret, n, k, 1, new ArrayList<Integer>());
return ret;
}
public void helper(ArrayList<ArrayList<Integer>> ret, int n, int k, int start , ArrayList<Integer> lst){
if(lst.size() == k){
ret.add(new ArrayList<Integer>(lst));
return;
}
for(int i=start; i <= n; i++){
lst.add(i);
helper(ret, n, k, i+1, lst);
lst.remove(lst.size() - 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment