LeetCode 077 Combinations
来源:互联网 发布:软件设计师视频下载 编辑:程序博客网 时间:2024/05/22 15:48
题目描述
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],
分析
递归,选择数字k次,每次选择的数字都比前一个大。
代码
int target;// 次数 Integer[] stack;// 存储每次排列 Integer[] nums;// 存储1~n List<List<Integer>> result;// 存储结果 public void search(int p) { // 若长度为k,则stack是其中一个结果,保存结果 if (p == target) { result.add(new ArrayList<Integer>(Arrays.asList(stack))); return; } // 对于nums(1~n)中的每个元素 for (Integer n : nums) { // 找到nums中第一个比stack最后元素大的元素 if (p > 0 && n <= stack[p - 1]) { continue; } // 找到下一个元素,递归 stack[p] = n; search(p + 1); } } public List<List<Integer>> combine(int n, int k) { target = k; nums = new Integer[n]; stack = new Integer[k]; for (int i = 0; i < nums.length; i++) { nums[i] = i + 1; } result = new ArrayList<List<Integer>>(); search(0); return result; }
1 0
- LeetCode: Combinations [077]
- LeetCode 077 Combinations
- LeetCode 077 Combinations
- LeetCode 077 Combinations
- leetcode 077 Combinations
- leetcode 077 —— 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
- PHP 性能分析第三篇: 性能调优实战
- MySql 5.6.20,安装后无法登陆的解决办法
- 深入理解Tagged Pointer
- Java中的享元(flyweight)设计模式
- Flash中启动Linux的方法
- LeetCode 077 Combinations
- 新版福昕阅读器(Foxit Reader)启动速度慢解决办法
- 打开MySQL数据库远程访问的权限
- Show slave status 详解
- timezone 0.4.3
- vim - Run python code in vim editor
- 编码常见问题及解决方式
- mysql批量删除指定后缀名的数据表
- 怎么能让div标签里面的p自动换行 [问题点数:30分,结帖人alleni123]