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],
]

题目链接:https://leetcode.com/problems/combinations/

class Solution {
public:
  void  fun(vector> &res,vector tmp,int s,int n, int k)
    {
        if(tmp.size()==k)
        {
            res.push_back(tmp);
        }
        else if(n-s+1>=k-tmp.size())
        {
            for(int i=s;i<=n;i++)
            {
                tmp.push_back(i);
                fun(res,tmp,i+1,n,k);
                tmp.pop_back();
            }
        }
        
    }
    vector> combine(int n, int k) {
        vector> res;
        vector tmp;
        fun(res,tmp,1,n,k);
        return res;
    }
};

 

你可能感兴趣的:(Leetcode)