[LeetCode] Combinations

本文探讨了一种典型的回溯法问题——从1到n中选取k个数的所有可能组合。通过定义部分解及其完成条件、寻找所有部分解的方法及递归调用时机,详细解析了算法实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A typical backtracking problem. For any backtracking problem, you need to be think about three ascepts:

  1. What is a partial solution and when is it finished? --- In this problem, the partial solution is a combination (sol). It is finished once it contains k elements.
  2. How to find all the partial solutions? --- In the following code, I simply traverse all the possible starting elements (start).
  3. When to make recursive calls? --- In the following code, once an element is added to the partial solution, we call the function to generate the remaining elements recursively.

Of course, remember to recover to the previous status once a partial solution is done. In the following code, line 18 (sol.pop_back()) is for this purpose.

The following should be self-explanatory :)

 1 class Solution {
 2 public:
 3     vector<vector<int>> combine(int n, int k) {
 4         vector<vector<int> > res;
 5         vector<int> sol;
 6         combination(1, n, k, sol, res);
 7         return res;
 8     }
 9 private:
10     void combination(int start, int n, int k, vector<int>& sol, vector<vector<int> >& res) {
11         if (k == 0) {
12             res.push_back(sol);
13             return;
14         }
15         for (int i = start; i <= n; i++) {
16             sol.push_back(i);
17             combination(i + 1, n, k - 1, sol, res);
18             sol.pop_back();
19         }
20     }
21 };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值