[leetcode] Combinations
来源:互联网 发布:数据保全系统 编辑:程序博客网 时间:2024/05/29 09:16
From : https://leetcode.com/problems/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],]
class Solution {public: void putRest(vector<vector<int>>& res, vector<int>& cur, int lastIndex, int needNum, int n) { if(needNum == 0) {res.push_back(cur); return;} for(int i=lastIndex+1; i<=n-needNum+1; i++) { cur.push_back(i); putRest(res, cur, i, needNum-1, n); cur.pop_back(); } } vector<vector<int>> combine(int n, int k) { vector<vector<int>> res; if(k>n || k<=0) return res; int last = n-k+1; for(int i=1; i<=last; i++) { vector<int> cur; cur.push_back(i); putRest(res, cur, i, k-1, n); } return res; }};
public class Solution {public List<List<Integer>> combine(int n, int k) {List<List<Integer>> ans = new ArrayList<List<Integer>>();if (n >= k && k > 0) {combine(1, k, n, new LinkedList<Integer>(), ans);}return ans;}private void combine(int I, int K, int N, LinkedList<Integer> cur,List<List<Integer>> ans) {if (K == 0) {ans.add(new ArrayList<Integer>(cur));return;}for (int i = I; i <= N - K + 1; ++i) {cur.add(i);combine(i + 1, K - 1, N, cur, ans);cur.removeLast();}}}
0 0
- LeetCode: Combinations
- LeetCode: Combinations
- LeetCode Combinations
- [Leetcode] Combinations
- [LeetCode] Combinations
- Leetcode: Combinations
- LeetCode Combinations
- [Leetcode] Combinations
- [Leetcode] Combinations
- [leetcode] Combinations
- [LeetCode]Combinations
- [leetcode]Combinations
- LeetCode-Combinations
- [leetcode] Combinations
- LeetCode - Combinations
- 【Leetcode】Combinations
- Leetcode: Combinations
- 【leetcode】Combinations
- UVA208
- runtime
- 关于从别处导入工程进eclipse后,res的values中styles中<style name="AppBaseTheme"出现问题解决办法
- web前端开发前景何去何从
- NSLayoutConstraint代码篇
- [leetcode] Combinations
- jni.h头文件学习笔记
- Android 数字动画
- Android应用层View绘制流程与源码分析
- 初学MFC——加载位图
- Notification基本通知的两种写法
- 分享8年开发经验,浅谈程序员职业规划
- php无法正常发送邮件
- linux命令收集(根据自己需要整理)