`

Combinations(c++实现)

 
阅读更多

 

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> > ret;
        if(n < k) return ret;
        vector<int> tmp;
        iter(0, n, k, tmp, ret);
        return ret;
    }
    
    void iter(int num, int &maxNum, int k, vector<int> tmp, vector<vector<int> > &ret) {
        if(k == 0) {
            ret.push_back(tmp);
            return;
        }
        if(k > 0) {
            for(int i = 1; i <= maxNum - num; ++i) {
                tmp.push_back(num+i);
                iter(num+i, maxNum, k-1, tmp, ret);
                tmp.pop_back();
            }
        }
    }
};

 

 

欢迎关注微信公众号——计算机视觉:

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics