LeetCode Solutions

77. Combinations

Time: $O(C(n, k) \cdot k)$

Space: $O(C(n, k))$

			

class Solution {
 public:
  vector<vector<int>> combine(int n, int k) {
    vector<vector<int>> ans;
    dfs(n, k, 1, {}, ans);
    return ans;
  }

 private:
  void dfs(int n, int k, int s, vector<int>&& path, vector<vector<int>>& ans) {
    if (path.size() == k) {
      ans.push_back(path);
      return;
    }

    for (int i = s; i <= n; ++i) {
      path.push_back(i);
      dfs(n, k, i + 1, move(path), ans);
      path.pop_back();
    }
  }
};
			

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

  private void dfs(int n, int k, int s, List<Integer> path, List<List<Integer>> ans) {
    if (path.size() == k) {
      ans.add(new ArrayList<>(path));
      return;
    }

    for (int i = s; i <= n; ++i) {
      path.add(i);
      dfs(n, k, i + 1, path, ans);
      path.remove(path.size() - 1);
    }
  }
}
			

class Solution:
  def combine(self, n: int, k: int) -> List[List[int]]:
    ans = []

    def dfs(s: int, path: List[int]) -> None:
      if len(path) == k:
        ans.append(path.copy())
        return

      for i in range(s, n + 1):
        path.append(i)
        dfs(i + 1, path)
        path.pop()

    dfs(1, [])
    return ans