Combination Sum III Leecode Java
2015-06-05 17:03
555 查看
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Ensure that numbers within the set are sorted in ascending order.
Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
看到这道题目的第一想法,就是用递归来做,但是直接递归会出现一个问题,难以满足题目中的递增条件,并且得到的结果会有重复值。所有,新用了一个helper函数,该函数增加了一个start参数,为当前取值的最小值。AP程序如下:
Ensure that numbers within the set are sorted in ascending order.
Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
看到这道题目的第一想法,就是用递归来做,但是直接递归会出现一个问题,难以满足题目中的递增条件,并且得到的结果会有重复值。所有,新用了一个helper函数,该函数增加了一个start参数,为当前取值的最小值。AP程序如下:
public class Solution { public List<List<Integer>> combinationSum3(int k, int n) { return helper(k, n, 1); } private List<List<Integer>> helper(int k,int n,int start){ List<List<Integer>> rst=new ArrayList<List<Integer>>(); if(n<0||n<start) return rst; if(k==1){ if(n>9) return rst; List<Integer> cur=new ArrayList<Integer>(); cur.add(n); rst.add(cur); }else { for(int i=start;i<9&&i<=n/(k);i++){ List<List<Integer>> curRst=helper(k-1, n-i, i+1); for(int j=0;j<curRst.size();j++){ List<Integer> curSingleRst=new ArrayList<Integer>(); curSingleRst.add(i); curSingleRst.addAll(curRst.get(j)); rst.add(curSingleRst); } } } return rst; } }
相关文章推荐
- Java多线程用法解析
- java返回编码格式
- java 线程池优先级调度
- java琐碎
- Java for LeetCode 154 Find Minimum in Rotated Sorted Array II
- Java Word 转 Pdf
- JAVA设计模式初探之组合模式
- 简易Java(18):属性能否重写?为什么?
- 在java类中执行main方法时,报内存溢出
- netbeans下将所有jar包打成一个,俗称fat jar
- Struts2开发步骤
- 疯狂Java学习笔记(74)------------线程池
- Eclipse基于注解方式搭建ssh框架
- Eclipse 快捷键
- Struts2的安装
- java之链表反转
- 《Java从入门到精通》第三章学习笔记
- org.springframework.web.context.request.RequestContextListener
- java 模式
- Spring整合Hibernate,使用注解,报错can't find hbm.cfg.xml