码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 77 组合

时间:2020-02-12 23:49:47      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:链接   problems   pop   个数   code   ack   bin   整数   bsp   

链接:https://leetcode-cn.com/problems/combinations

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

示例:

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

 

这道题是用DFS来做的,我们将数按照从小到大的顺序加入到path中,保持后加入的数比前面加入的数要大,这样可以保证不重不漏。要记得回溯喔。

 

c++代码如下:

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

 

LeetCode 77 组合

标签:链接   problems   pop   个数   code   ack   bin   整数   bsp   

原文地址:https://www.cnblogs.com/hellosnow/p/12301793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!