import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class LeetCode0077 {
	public List<List<Integer>> combine(int n, int k) {
		List<List<Integer>> result = new ArrayList<List<Integer>>();
		if (n == 0 || k == 0 || n < k) {
			return result;
		}
		Set<Integer> set = new HashSet<Integer>();
		for (int i = 1; i <= n; i++) {
			set.add(i);
		}
		dfs(n, k, result, new LinkedList<Integer>(), set);
		return result;

	}

	private void dfs(int n, int k, List<List<Integer>> result, LinkedList<Integer> current, Set<Integer> set) {

		if (current.size() == k) {
			result.add(new LinkedList<Integer>(current));
			return;
		}

		for (int i = current.isEmpty() ? 1 : current.getLast(); i <= n; i++) {
			if (set.contains(i)) {
				current.add(i);
				set.remove(i);
				dfs(n, k, result, current, set);
				current.removeLast();
				set.add(i);
			}
		}
	}

	public static void main(String[] args) {
		LeetCode0077 leetcode = new LeetCode0077();
		List<List<Integer>> result = leetcode.combine(4, 2);
		for (int i = 0; i < result.size(); i++) {
			for (int j = 0; j < result.get(i).size(); j++) {
				System.out.print(result.get(i).get(j) + " ");
			}
			System.out.println();
		}
	}
}

@@ -42,88 +42,11 @@
 til.
-HashSet;%0Aimport java.util.LinkedList;%0Aimport java.util.List;%0Aimport java.util.Se
+Lis
 t;%0A%0A
@@ -249,111 +249,17 @@
 %09%09%7D%0A
-%09%09Set%3CInteger%3E set = new HashSet%3CInteger%3E();%0A%09%09for (int i = 1; i %3C= n; i++) %7B%0A%09%09%09set.add(i);%0A%09%09%7D%0A
 %09%09dfs(
+1, 
 n, k
@@ -268,30 +268,29 @@
 result, new 
-Linked
+Array
 List%3CInteger
@@ -292,21 +292,16 @@
 teger%3E()
-, set
 );%0A%09%09ret
@@ -312,17 +312,16 @@
 result;%0A
-%0A
 %09%7D%0A%0A%09pri
@@ -334,24 +334,35 @@
 oid dfs(int 
+start, int 
 n, int k, Li
@@ -387,22 +387,21 @@
 result, 
-Linked
+Array
 List%3CInt
@@ -417,56 +417,24 @@
 rent
-, Set%3CInteger%3E set
 ) %7B%0A
-%0A
 %09%09if (
-current.size()
+k
  == 
-k
+0
 ) %7B%0A
@@ -455,14 +455,13 @@
 new 
-Linked
+Array
 List
@@ -503,156 +503,88 @@
 %0A%0A%09%09
-for (int i = current.isEmpty() ? 1 : current.getLast(); i %3C= n; i++) %7B%0A%09%09%09if (set.contains(i)) %7B%0A%09%09%09%09current.add(i);%0A%09%09%09%09set.remove(i
+if (start %3E n) %7B%0A%09%09%09return;%0A%09%09%7D%0A%0A%09%09current.add(start
 );%0A
-%09%09
 %09%09dfs(
-n, k
+start + 1, n, k - 1
 , re
@@ -600,18 +600,11 @@
 rent
-, set
 );%0A
-%09%09
 %09%09cu
@@ -619,40 +619,70 @@
 move
-Last();%0A%09%09%09%09set.add(i);%0A%09%09%09%7D%0A%09%09%7D
+(current.size() - 1);%0A%09%09dfs(start + 1, n, k, result, current);
 %0A%09%7D%0A

Modify LeetCode0077.java