77. Combinations

Problem:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
Analysis:
Very easy DFS.

Solution:

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        if (k > n) return res;
        dfs(res, new ArrayList<>(), n, 1, k);
        return res;
    }

    private void dfs(List<List<Integer>> res, List<Integer> list, int n, int start, int k) {
        if (list.size() == k) {
            res.add(new ArrayList<>(list));
        } else {
            for (int i = start; i <= n; i++) {
                list.add(i);
                dfs(res, list, n, i + 1, k);
                list.remove(list.size() - 1);
            }
        }
        
    }
}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List