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

Backtracking 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);
        }
    }

Last updated