Discription
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],
]
思路
基于分治思想:
{1,2,⋯,i−1,i,i+1,⋯,n}
现假设已经在
1,2,⋯,i−1
挑选了
ni−1
个数,考虑
i
,有两种情况:
- 选择
i ,再从 i+1,⋯,n 挑选 k−ni−1−1 个数;- 不选择
i
,再从
i+1,⋯,n 挑选 k−ni−1 个数; 对于 {1,2,3} ,其递归过程如下图
时间复杂度: ?
空间复杂度:? 代码
class Solution { public: void dfs(vector<int> &tmp, vector<vector<int>> &res, int start, int end, int k) { if (tmp.size() == k) { res.push_back(tmp); return; } if (start > end) return; // 选择start tmp.push_back(start); dfs(tmp, res, start + 1, end, k); // 不选start tmp.pop_back(); dfs(tmp, res, start + 1, end, k); } vector<vector<int>> combine(int n, int k) { vector<int> tmp; vector<vector<int>> res; dfs(tmp, res, 1, n, k); return res; } };
扩展
考虑包含重复元素的组合,如 1,1,2,3 中两个数的所有组合
方案:排序+选择策略(前一个重复元素被选中时,当前重复元素才可以被选中)
- 不选择
i
,再从