[leetcode-77-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],
]

思路:

使用回溯法。

    void combine(vector<vector<int>>& result,vector<int>& temp,int n,int k,int start)
    {
        if (temp.size() == k)
        {
            result.push_back(temp);
            return;
        }
        for (int i = start; i <= n;i++)
        {
            temp.push_back(i);//插入
            combine(result, temp,n,k,i+1);//是i+1 不是start+1
            temp.pop_back();//弹出
        }    
    }
    vector<vector<int>> combine(int n, int k)
    {
        vector<vector<int>>result;
        if (n < k) return result;
        vector<int> temp;
        combine(result, temp, n, k, 1);
        return result;
    }

参考:

https://discuss.leetcode.com/topic/3950/my-shortest-c-solution-using-dfs

原文地址:https://www.cnblogs.com/hellowooorld/p/6640743.html