博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Combinations
阅读量:7126 次
发布时间:2019-06-28

本文共 1504 字,大约阅读时间需要 5 分钟。

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],]

参考别人的code, 看似不难的题,其实有点小难的,recursive function并不好写。思想还是:From this example, we can see that in the first position of the resulting combinations we can chose number 1-5.  Assume that we chose 1 for the 1 position of the combination, then we can choose 2-5 for the second position.  Till we chosen numbers for all position, we can have one possible combination.

However, when we chose 3 for the first position and 5 for the second position, we don't have any other number to choose for the 3rd position. (former number must be smaller than the following number).

1 public class Solution { 2     public ArrayList
> combine(int n, int k) { 3 ArrayList
set = new ArrayList
(); 4 ArrayList
> sets= new ArrayList
>(); 5 6 if (n < k) return sets; 7 helper(set, sets, 1, n, k); 8 return sets; 9 }10 11 public void helper(ArrayList
set, ArrayList
> sets, int starter, int n, int k) {12 if (set.size() == k) {13 sets.add(new ArrayList
(set));14 return;15 }16 17 else {18 19 for (int j = starter; j <= n; j++) {20 set.add(j);21 helper(set, sets, j+1, n, k);22 set.remove(set.size()-1);23 }24 }25 }26 }

sets.add(new ArrayList<Integer>(set)); 要特别注意,我写成sets.add(set)就会在以下情况报错:input为: 1,1; expected:[[1]], output: [[]]

转载地址:http://pzeel.baihongyu.com/

你可能感兴趣的文章
Java必须了解的“递归”与“IO流”!!!
查看>>
Http协议状态码
查看>>
css3单冒号和双冒号的区别
查看>>
小X与缩写
查看>>
第一次团队会议
查看>>
018-请你说一下设计测试用例的方法
查看>>
android 链接mysql数据库
查看>>
CAKeyframeAnimation 旋转动画
查看>>
学习python的第二天
查看>>
Python 基础语法
查看>>
(转)被忽略的Main函数
查看>>
配置spring文件时候出现的小问题
查看>>
微服务系统中的认证策略
查看>>
Java EE
查看>>
Python验证码识别处理实例(转)
查看>>
easyui插件显示问题
查看>>
Flask学习【第3篇】:蓝图、基于DBUtils实现数据库连接池、上下文管理等
查看>>
asp.net core1.1的PlatformAbstraction源码
查看>>
OWL库(叙词表构建本体OWL库)程序说明文档
查看>>
[日常] MySQL内存不足启动失败的解决方法
查看>>