Skip to content

Latest commit

 

History

History
53 lines (44 loc) · 849 Bytes

0077._combinations.md

File metadata and controls

53 lines (44 loc) · 849 Bytes

77. Combinations

难度: Medium

刷题内容

原题连接

内容描述

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

示例:

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

解题方案

思路 1

回溯寻找所有组合。
 void dfs(int k, int index, int n, vector<int>& path, vector<vector<int>>& ans){
    if(k==0){
        ans.push_back(path);
        return ;
    }
    for(int i=index;i<=n;i++){
        path.push_back(i);
        dfs(k-1, i+1, n, path, ans);
        path.pop_back();
    }
}
vector<vector<int>> combine(int n, int k) {
    vector<vector<int>> ans;
    vector<int> path;
    dfs(k, 1, n, path, ans);
    return ans;
}