LeetCode题解——77:组合

题目相关

题目链接

LeetCode中国,https://leetcode-cn.com/problems/combinations/。注意需要登录。

题目描述

给定两个整数 n 和 k,返回 1 ... 中所有可能的 k 个数的组合。

示例

输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

题目分析

题意分析

数学中的组合。即列出 \binom{k}{n} 的所有可能。

一个标准的模板 DFS 题,难度入门级。

样例数据分析

略,没什么需要特别分析的。

算法思路

从小到大的选出 k 个数字,这样答案一定是确定的。有如下几个方面细节。

搜索终止条件

终止条件必然是搜索出的数字个数达到 k。

搜索函数参数

1、一个数组,表示现在已经搜索出几个数字。

2、一个整数表示开始搜索的数字 start。

3、一个整数表示搜索的终止数 n。这个可以用全局变量来表示,如果用全局变量这个参数可以省略。

4、还剩下几个数需要搜索 left。

因此,本题的 dfs() 函数的原型可以是如下的表示:

//参数1:path存放已经搜索出了几个数据
//参数2:start表示从哪个数字开始搜索
//参数3:n表示搜索的最大数据
//参数4:left还剩下几个数没有搜索到
void dfs(vector<int> &path, int start, int n, int left);

开始调用方式

//从0开始搜索,搜索到数据n,一共搜索k个数字
dfs(path, 0, n, k);

回溯

        path.push_back(i);//将数据i保存到path中
        dfs(path, i+1, n, k-1);
        path.pop_back();//回溯

AC 参考代码

class Solution {
public:
    vector<vector<int>> ans;//答案
 
    vector<vector<int>> combine(int n, int k) {
        vector<int> path;
 
        dfs(path, 1, n, k);
 
        return ans;
    }
 
    void dfs(vector<int> &path, int start, int n, int k) {
        if (0==k) {
            //搜索到了
            ans.push_back(path);
            return;
        }
 
        for (int i=start; i<=n; i++) {
            //加入当前数据
            path.push_back(i);
            dfs(path, i+1, n, k-1);
            path.pop_back();//回溯
        }
    }
};
发布了239 篇原创文章 · 获赞 291 · 访问量 107万+

猜你喜欢

转载自blog.csdn.net/justidle/article/details/104931818
今日推荐