给定两个整数 n
和 k
. 返回从 1, 2, ... , n
中选出 k
个数的所有可能的组合.
样例
样例 1:
输入: n = 4, k = 2
输出: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
样例 2:
输入: n = 4, k = 1
输出: [[1],[2],[3],[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>> ret;
vector<int> tmp;
vector<int> nums;
for(int i = 1; i <=n; i++)
{
nums.push_back(i);
}
//sort(nums.begin(), nums.end());
backtrack(ret, tmp, nums, 0,k);
return ret;
}
void backtrack(vector<vector<int>>& ret, vector<int> &tempList, vector<int>& nums, int start,int k)
{
if(tempList.size() == k)
ret.push_back(tempList);
for(int i = start; i < nums.size(); i++)
{
tempList.push_back(nums[i]);
backtrack(ret, tempList, nums, i+1,k);
tempList.erase(tempList.begin() + tempList.size() - 1);
}
}
};