LeetCode -- Combinations
来源:互联网 发布:java专业基础课程 编辑:程序博客网 时间:2024/06/03 20:18
题目描述:
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的子集。例如小于3的子集有{{},{1},{2},{3},{1,2},{1,3},{2,3},{1,2,3}},而当k=2时,符合条件的子集为[{1,2},{2,3},{1,3}]。
已知k的取值范围是[1,n]。
思路:
对[1,n]每个元素进行回溯。
每次添加当前元素i并进入新过程后还原状态(删除i)。
如果当前集合长度等于k添加到结果集并返回。
实现代码:
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的子集。例如小于3的子集有{{},{1},{2},{3},{1,2},{1,3},{2,3},{1,2,3}},而当k=2时,符合条件的子集为[{1,2},{2,3},{1,3}]。
已知k的取值范围是[1,n]。
思路:
对[1,n]每个元素进行回溯。
每次添加当前元素i并进入新过程后还原状态(删除i)。
如果当前集合长度等于k添加到结果集并返回。
实现代码:
public class Solution { public IList<IList<int>> Combine(int n, int k) { var result = new List<IList<int>>(); Do(1, n, k, new List<int>(), ref result); return result; } private void Do(int start, int n, int k, List<int> current, ref List<IList<int>> result) { if(current.Count == k){ result.Add(new List<int>(current)); return; } for(var i = start; i <=n ;i ++){ current.Add(i); Do(i+1, n, k, current, ref result); current.Remove(current.Last()); } }}
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
- Tkinter实现Listbox单行多值
- 指令汇B新闻客户端开发(三) 下拉刷新
- Protel99se不能添加元件库 File is not recognized
- hpuoj 1720: 感恩节KK专场——面试难题 (贪心)
- 最新研发,谷歌最新动态!!
- LeetCode -- Combinations
- 在VMWare虚拟机中安装ubuntu系统后,登进系统,桌面没有任何图标,可以用xshell远程连接
- Jlink隔离器,ARM仿真器隔离,Jlink,Nu-link,ULINK的隔离,Cortex-M系列隔离仿真
- hash表
- UIScrollView
- oracle事务隔离机制
- HDU 搬砖
- LeetCode -- Find the Duplicate Number
- 使用SIGALRM信号为阻塞操作设置超时