首页 > 代码库 > 【Leetcode】Combinations
【Leetcode】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], ]
思路:采用深度优先搜索策略,先取1,然后从[2, 4]区间内取一个;取2,然后从[3, 4]区间取一个;取3,然后从[4]区间中取一个。
代码一:
class Solution { public: vector<vector<int> > combine(int n, int k) { vector<vector<int>> result; if(n < k || k <= 0) return result; return combine_helper(1, n, k); } private: vector<vector<int>> combine_helper(int start, int end, int k) { vector<vector<int>> result; if(k == 1) { for(int i = start; i <= end; i++) { vector<int> temp; temp.push_back(i); result.push_back(temp); } return result; } for(int i = start; i <= end - k + 1; i++) { vector<vector<int>> temp; temp = combine_helper(i + 1, end, k - 1); for(int j = 0; j < temp.size(); j++) { temp[j].insert(temp[j].begin(), i); result.push_back(temp[j]); } } return result; } };
代码二:另一种相对比较简洁的递归写法
class Solution { public: vector<vector<int> > combine(int n, int k) { vector<vector<int> > result; vector<int> path; dfs(n, k, 1, 0, path, result); return result; } private: // start,开始的数, cur,已经选择的数目 static void dfs(int n, int k, int start, int cur, vector<int> &path, vector<vector<int> > &result) { if (cur == k) result.push_back(path); for (int i = start; i <= n; ++i) { path.push_back(i); dfs(n, k, i + 1, cur + 1, path, result); path.pop_back(); } } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。