Combinations

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>>res;
		if(k==0) return vector<vector<int>>(1,vector<int>());
        if(n==k){
            vector<int>tmp(n);
            for(int i=0;i<n;i++) tmp[i]=i+1;
            res.push_back(tmp);
            return res;
        }else if(n>k){
            vector<vector<int>> preres=combine(n-1,k-1);
            int nn=preres.size();
            for(int i=0;i<nn;i++){
                preres[i].push_back(n);
            }
            vector<vector<int>> preres2=combine(n-1,k);
            int n2=preres2.size();
            for(int i=0;i<n2;i++){
                preres.push_back(preres2[i]);
            }
            return preres;
        }
    }
};


你可能感兴趣的:(Combinations)