[LeetCode] 77. Combinations 全组合
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], ]
给两个数字n, k,返回所有由[1...n]中的k数字组合的可能解。
解法1: 递归
解法2: 迭代
C++: Recursion
class Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> res; vector<int> out; helper(n, k, 1, out, res); return res; } void helper(int n, int k, int level, vector<int>& out, vector<vector<int>>& res) { if (out.size() == k) res.push_back(out); for (int i = level; i <= n; ++i) { out.push_back(i); helper(n, k, i + 1, out, res); out.pop_back(); } } };
C++: Iteration
class Solution { public: vector<vector<int> > permute(vector<int> &num) { vector<vector<int> > res; permuteDFS(num, 0, res); return res; } void permuteDFS(vector<int> &num, int start, vector<vector<int> > &res) { if (start >= num.size()) res.push_back(num); for (int i = start; i < num.size(); ++i) { swap(num[start], num[i]); permuteDFS(num, start + 1, res); swap(num[start], num[i]); } } };
类似题目:
[LeetCode] 17. Letter Combinations of a Phone Number 电话号码的字母组合