组合

给出两个整数n和k,返回从1......n中选出的k个数的组合。

样例

例如 n = 4 且 k = 2

返回的解为:

[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]

class Solution {
public:
    /**
     * @param n: Given the range of numbers
     * @param k: Given the numbers of combinations
     * @return: All the combinations of k numbers out of 1..n
     */
    vector<vector<int> > combine(int n, int k) {
        // write your code here
        vector<vector<int> > result;
        vector<int> value;
        int count = 0;
        visit(n, 1, k, count, value, result);

        return result;
    }
private:
    void visit(int n, int num, int k, int count, vector<int> &value, vector<vector<int> > &result)
    {
        if (count == k)
        {
            result.push_back(value);
            return;
        }
        if (num > n)
        {
            return;
        }

        value.push_back(num);
        visit(n, num+1, k, count+1, value, result);
        value.pop_back();
        visit(n, num+1, k, count, value, result);
    }
};


你可能感兴趣的:(组合)