# DFS实现排列组合

LeetCode有两个问题分属于组合、排列：77. Combinations46. Permutations

## 组合

public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<>();
if (n <= 0 || n < k) {
return result;
}
List<Integer> tmp = new ArrayList<>();
dfs(n, k, 1, tmp, result);
return result;
}

// DFS for combination
private void dfs(int n, int k, int start,
List<Integer> tmp, List<List<Integer>> result) {
if (tmp.size() == k) {
return;
}
for (int i = start; i <= n; i++) {
dfs(n, k, i + 1, tmp, result);
tmp.remove(tmp.size() - 1); // remove the last
}
}


## 排列

DFS实现排列与组合相类似，唯一不同之处在于，节点i与其他所有节点都连接。因此，所构造的图是一个完全连通图。DFS实现排列如下：

public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if (nums.length == 0) {
return result;
}
List<Integer> tmp = new ArrayList<>();
dfs(nums, tmp, result);
return result;
}

// DFS for permutation
private void dfs(int[] nums, List<Integer> tmp,
List<List<Integer>> result) {
int n = nums.length;
if (tmp.size() == n) {
return;
}
for (int i = 0; i < n; i++) {
// nums[i] has not been visited
if (!tmp.contains(nums[i])) {