C++ 练习题 <combinations>

2020-12-13 02:04

阅读:415

标签:ble   sub   push   util   oss   numbers   练习题   void   integer   

[编程题] combinations

时间限制:1秒

空间限制:32768K


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

For example,
If n = 4 and k = 2, a solution is:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

class Solution {
public:
    vectorint> > combine(int n, int k) {
        vectorint> > ans;
        vectorint> temps;
        combineUtil(ans, temps,n,1,k);
        return ans;
    }
    void combineUtil(vectorint>>& ans,vectorint>& temps,int n,int left,int k){
        if (k == 0)
        {
            ans.push_back(temps);
            return;
        }
        else
        {
            for (int i=left;i)
            {
                temps.push_back(i);
                combineUtil(ans,temps,n,i+1,k-1);
                temps.pop_back();
            }
        }
    }
};

 


C++ 练习题

标签:ble   sub   push   util   oss   numbers   练习题   void   integer   

原文地址:https://www.cnblogs.com/sisi-science/p/11025763.html


评论


亲,登录后才可以留言!