LeetCode Combinations
来源:互联网 发布:淘宝宝贝详情模板代码 编辑:程序博客网 时间:2024/06/03 17:16
Description:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Solution:
排列组合,也是前面已经用到过的方法,用DFS来解决。
注意提一点,组合因为是有一个特殊要求,即为选出的点有且仅有k个,所以每一层的循环要特别当心,当前这个DFS层所能选取的点的范围应当是[currentIndex+1, n+1-(k-count) ],利用循环的范围来保证,当我的currentIndex走到n+1也就是结尾的时候,count与k相等。只不过这里最终提交,利用系统栈会爆栈,所以为了简洁,就先用了count==k的结束标记。
参数说明:currentIndex当前已经到了第几个数字的下标,count是已经选了几个数字的个数,currentList是记录了当前选出了那几个数字,count=currentList.size(),n和k则是和题目中所给的一样。
import java.util.*;public class Solution {List<List<Integer>> list;public List<List<Integer>> combine(int n, int k) {list = new ArrayList<List<Integer>>();dfs(0, 0, new ArrayList<Integer>(), n, k);return list;}void dfs(int currentIndex, int count, ArrayList<Integer> currentList,int n, int k) {// if (currentIndex == n + 1) {if (count == k) {list.add(new ArrayList(currentList));return;} else {for (int i = currentIndex + 1; i <= n + 1 - (k - count); i++) {currentList.add(i);dfs(i, count + 1, currentList, n, k);currentList.remove(currentList.size() - 1);}}}}
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
- 【Linux 内核网络协议栈源码剖析】网络栈主要结构介绍(socket、sock、sk_buff,etc)
- 【c语言】不能使用循环语句和判断语句,求1-100所有整数的和
- 棋盘的完美覆盖(多米诺骨牌完美覆盖)&&幻方(魔方阵)
- c++中的向量一般操作
- Linux 如何支持远程图形
- LeetCode Combinations
- MySQL运行状态show status详解
- 【数据结构】实现栈的各种算法
- 使用DOM解析XML文件
- 死锁的产生与解决
- java ReadWriteLock用法示例
- SylixOS 经得起检验的国产操作系统 (二)
- 数据库复习8——并发
- Qt调色板和样式表