Combinations

Posted IIcyZhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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) 
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        result.clear();
        got.clear();
        record.clear();
        if (k == 0) 
            return result;
        
        record = vector<int>(n, 0);
        max = n;
        trace_back(k);
        return result;
    
    
    void trace_back(int n) 
        if (0 == n) 
            result.push_back(got);
            return;
        
        for (int i = 1; i <= max; ++i) 
            if (record[i-1] == 0) 
                if (!got.empty() && got[got.size() -1] > i) 
                    continue;
                
                record[i-1] = 1;
                got.push_back(i);
                trace_back(n-1);
                got.pop_back();
                record[i-1] = 0;
            
        
    
    vector<vector<int> > result;
    vector<int> got;
    vector<int> record;
    int max;
;


以上是关于Combinations的主要内容,如果未能解决你的问题,请参考以下文章

itertools mode 之 combinations用法

77. Combinations

python 全排列combinations和permutations函数

[Locked] Factor combinations

254. Factor Combinations

77. Combinations