简单的限定个数组合生成 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],
]

思路:backtrack。由于状态容易now是引用类型传入传出的,所以用完之后要恢复原样。

class Solution {
public:
    vector<vector<int> > combine(int n, int k) {
        vector<vector<int> > com;
        if(n < k)
            return com;
        vector<int> now;
        produce(com, now, n, k, 0, 1);
        return com;
    }
    
    void produce(vector<vector<int> > &com, vector<int> &now, int n, int k, int count, int from)
    {
        if(count == k)
        {
            com.push_back(now);
            return;
        }
        if(from > n)
            return;
        
        produce(com, now, n, k, count, from+1);
        now.push_back(from);
        produce(com, now, n, k, count+1, from+1);
        now.pop_back(); //注意要将now改回原样
    }
};


你可能感兴趣的:(简单的限定个数组合生成 Combinations)