42_leetcode_Combinations

来源:互联网 发布:芒果tv最近新网络剧 编辑:程序博客网 时间:2024/04/29 19:09

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, 

1, 2; 1, 3; 1, 4; 2, 3; 2, 4; 3,4

1:特殊情况的考虑,2:采用递归的方式,首先选择当前的数字,之后在后面的数组中选择k-1;或者不选择当前的数字,而在数组后面选择k个数字;3:注意递归结束条件以及成功选择一组结束的条件

    vector<vector<int> > combine(int n, int k) {        vector<vector<int> > result;                if(n <= 0 || k > n)        {            return result;        }                vector<int> temp;                combineCore(n, k, 1, temp, result);                return result;    }        void combineCore(int n, int k, int index, vector<int>& temp, vector<vector<int> >& result)    {        if(k == 0)        {            result.push_back(temp);            return;        }             if(index > n)        {            return;        }                temp.push_back(index);        combineCore(n, k - 1, index + 1, temp, result);        temp.pop_back();        combineCore(n, k, index + 1, temp, result);    }


0 0
原创粉丝点击