# LeetCode Combinations: DFS vs Iterative

## Overview

This LeetCode Combinations could be solved by using backtracking/DFS: C(n,k) = C(n-1, k-1) U n + C(n-1,k) and it could be done in iterative way too.

## LeetCode Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.

For example,
If n = 4 and k = 2, a solution is:

```[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]```

## Analysis: DFS vs Iterative

1) DFS in standard way: Since we need to permute all the possible combinations, we could adopt the general framework of backtracking approach to do it: Suppose answer[k] is a general legal combination, we need to construct all the candidates for answer[0], … answer[k-1], backtracking is exactly the way to do this, and  remember to keep the candidates sorted to ensure there is no duplicates such as [1, 2] and [2, 1]. The following source code is accepted by LeetCode OJ to pass this Combinations problem:

2) DFS by using the formula: select k numbers from a set of n numbers, from mathematical angle, we know the following formula:

C(n,k) = C(n-1, k-1) U n + C(n-1,k)

By implementing the above formula, the following code is accepted by LeetCode OJ to pass this Combinations problem too:

3) Iterative Implementation: we could actually generate the subset level by level, first generate the subset of size 1, and then of size 2, this could be done by directly translating the dfs approach in (1) into iterative way, the following code could be accepted by LeetCode OJ to pass this Combinations problem as well:

## Summary

This LeetCode Combinations could be solved by using backtracking/DFS: C(n,k) = C(n-1, k-1) U n + C(n-1,k) and it could be done in iterative way too.

Written on April 14, 2013