77. Combinations

Medium

nCr=n!r!(nr)!_nC_r=\frac{n!}{r!(n-r)!}

Problem:

Given a total number n, return all combinations of k elements.

Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]

Explanation: There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.

https://leetcode.com/problems/combinations/arrow-up-right

Solution:

Backtracking

  1. Start the next number from the last number in the current list: Instead of always starting from 1, you can start from the next number after the last number in the current list. This way, you avoid generating duplicate combinations.

  2. Early stopping: If there are not enough numbers left to reach a total of k numbers, you can stop early. For example, if n = 5, k = 3, and the current list is [4], there's no way to pick 3 numbers, so you can stop.

chevron-rightTime Limit Exceededhashtag

itertools Module

Reference: itertools Module

Last updated