Skip to content

Instantly share code, notes, and snippets.

@b27lu
Created February 12, 2014 17:38
Show Gist options
  • Save b27lu/8960558 to your computer and use it in GitHub Desktop.
Save b27lu/8960558 to your computer and use it in GitHub Desktop.
Combination question of leetcode
public class Solution {
public ArrayList<ArrayList<Integer>> combine(int n, int k) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(n <= 0 || k<=0)
return result;
ArrayList<Integer> temp = new ArrayList<Integer>();
dfsWorker(n, k, result, temp, 1);
return result;
}
public void dfsWorker(int n, int k, ArrayList<ArrayList<Integer>> result, ArrayList<Integer> temp, int currentPosition){
for(int i = currentPosition;i<=n;i++){
temp.add(i);
if(temp.size() == k)
result.add(new ArrayList<Integer>(temp));
else
dfsWorker(n, k, result, temp, i+1);
//remove the elements from temp before return
temp.remove(temp.size()-1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment