Combinations [leetcode]

描述: 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],

]

思路:模拟手工组合C(n,k)的方法, 用pos 标记当前的位置,从pos ,n 中间选取k个数据,

class Solution {

public:



    void choose(int n, int k, int pos, vector<int>&array, vector<vector<int> >&ret)

    {

        if(k == 0)

        {

            ret.push_back(array);

            return;

        }



        for(int i = pos ; i <= n; ++i)

        {

            array.push_back(i);

            choose(n, k-1, i+1, array, ret);

            array.resize(array.size()-1);

        }



        return;

    }



    vector<vector<int> > combine(int n, int k) 

    {

        vector<vector<int> > ret ;

        if(n == 0 || k == 0 || k > n)

            return ret;



        vector<int> array;

        choose(n, k, 1, array, ret);

        return ret;

    }

};

 

 

你可能感兴趣的:(LeetCode)