152 · Combinations
Algorithms
Medium
Description
Given two integers n and k. Return all possible combinations of k numbers out of 1, 2, … , n.
You can return all combinations in any order, but numbers in a combination should be in ascending order.
Example
Example 1:
Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Example 2:
Input: n = 4, k = 1
Output: [[1],[2],[3],[4]]
Related Knowledge
学习《算法求职课——百题精讲》课程中的14.5组合-视频讲解相关内容 ,了解更多相关知识!
Tags
Related Problems
34
N-Queens II
Medium
33
N-Queens
Medium
653
Expression Add Operators
Hard
740
Coin Change 2
Medium
739
24 Game
Hard文章来源:https://www.toymoban.com/news/detail-745694.html
解法1:文章来源地址https://www.toymoban.com/news/detail-745694.html
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
* we will sort your return value in output
*/
vector<vector<int>> combine(int n, int k) {
vector<int> sol;
vector<vector<int>> sols;
helper(n, k, 1, sols, sol);
return sols;
}
private:
void helper(int n, int k, int index, vector<vector<int>> &sols, vector<int> &sol) {
if (sol.size() == k) { //关键是这一行
sols.push_back(sol);
return;
}
for (int i = index; i <= n; i++) {
sol.push_back(i);
helper(n, k, i + 1, sols, sol);
sol.pop_back();
}
}
};
到了这里,关于Lintcode 152 · Combinations (组合好题)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!