首页 > 编程语言 > 详细

C++ 练习题 <combinations>

时间:2019-06-14 23:25:25      阅读:169      评论:0      收藏:0      [点我收藏+]
[编程题] 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:
    vector<vector<int> > combine(int n, int k) {
        vector<vector<int> > ans;
        vector<int> temps;
        combineUtil(ans, temps,n,1,k);
        return ans;
    }
    void combineUtil(vector<vector<int>>& ans,vector<int>& temps,int n,int left,int k){
        if (k == 0)
        {
            ans.push_back(temps);
            return;
        }
        else
        {
            for (int i=left;i<=n;i++)
            {
                temps.push_back(i);
                combineUtil(ans,temps,n,i+1,k-1);
                temps.pop_back();
            }
        }
    }
};

 


C++ 练习题 <combinations>

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!