Created
February 12, 2014 17:38
-
-
Save b27lu/8960558 to your computer and use it in GitHub Desktop.
Combination question of leetcode
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
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