leetcode-77. Combinations 组合

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

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

示例:

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

 思路:dfs

class Solution {
public:
    void dfs(int n,int k,int cur,vector out,vector> & res)
    {
        if(out.size()==k)
        {
            res.push_back(out);
            return;
        }
        for(int i=cur;i<=n;++i)
        {
            out.push_back(i);
            dfs(n,k,i+1,out,res);
            out.pop_back();
        }
    }
    vector> combine(int n, int k) {
        vector> res;
        dfs(n,k,1,{},res);
        return res;
        
    }
};

 

你可能感兴趣的:(数据结构/算法/刷题,#)