给定两个整数 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<int> temp;
for (int i = 1; i <= n; i++) {//将所有元素放进数组
/* code */
temp.push_back(i);
}
vector<vector<int>> result;
vector<int> nums;
dfs(temp,result,0,nums,k);
return result;
}
void dfs(vector<int> &temp,vector<vector<int>> &result,int index,vector<int> &nums,int k)
{
if(nums.size()==k) result.push_back(nums);
for (int i = index; i < temp.size(); i++) {//添加元素后返回删除元素
/* code */
nums.push_back(temp[i]);
dfs(temp,result,i+1,nums,k);
nums.pop_back();
}
}
};
优化后
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>> result;
vector<int> nums;
dfs(n,result,1,nums,k);
return result;
}
void dfs(int n,vector<vector<int>> &result,int index,vector<int> &nums,int k)
{
if(nums.size()==k) result.push_back(nums);
for (int i = index; i <= n; i++) {//添加元素后返回删除元素
/* code */
nums.push_back(i);
dfs(n,result,i+1,nums,k);
nums.pop_back();
}
}
};