[LeetCode] Combinations [38]

时间:2023-03-08 22:16:28
[LeetCode] Combinations [38]

称号

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],
]

原题链接(点我)

解题思路

组合问题,老思路---递归加循环,这个是组合里面比較简单的。

代码实现

class Solution {
public:
vector<vector<int> > combine(int n, int k) {
vector<vector<int> > ret;
helper(k, 1, n, vector<int>(), ret);
return ret;
}
void helper(int k, int start, int n, vector<int> part, vector<vector<int> > &ret){
if(k==part.size()){
ret.push_back(part);
return;
}
for(int i=start; i<=n; ++i){
part.push_back(i);
helper(k, i+1, n, part, ret);
part.pop_back();
}
}
};
假设你认为本篇对你有收获,请帮顶。

另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
你能够搜索公众号:swalge 或者扫描下方二维码关注我
[LeetCode] Combinations [38]
(转载文章请注明出处: http://blog.csdn.net/swagle/article/details/30761165
)

版权声明:本文博主原创文章。博客,未经同意不得转载。