> For the complete documentation index, see [llms.txt](https://junnie.gitbook.io/nine-chapter/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://junnie.gitbook.io/nine-chapter/4.depth-first-search/152combinations.md).

# 77.Combinations (M)

https\://leetcode.com/problems/combinations/

## 1.Description(Medium)

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

**Example**

For example,\
If n = 4 and k = 2, a solution is:\
\[\[2,4],\[3,4],\[2,3],\[1,2],\[1,3],\[1,4]]

[**Tags**](http://www.lintcode.com/en/problem/combinations/#tags)

[Backtracking](http://www.lintcode.com/tag/backtracking/) [Array](http://www.lintcode.com/tag/array/)

## 2.Code

经典的dfs+backtracking

```
public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<>();
        if (n < k ){
            return result;
        }
        List<Integer> path = new ArrayList<Integer>();
        backtrack(result,path,k,1,n);
        return result;
    }

    public void backtrack(List<List<Integer>> result,
                          List<Integer> path,
                          int k,
                          int start,
                          int n) {
        if (path.size() == k){
            result.add(new ArrayList<Integer>(path));
            return;
        }
        for (int i = start; i <= n; i++) {
            path.add(i);
            backtrack(result, path, k, i+1, n);
            path.remove(path.size()-1);
        }
    }
```
