Combination Sum III
2015-06-01 14:50
393 查看
Find all possible combinations of k numbers that add up to a number n, given that only numbersfrom 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 = 7Output:
[[1,2,4]]Example 2:Input: k = 3, n = 9Output:
[[1,2,6], [1,3,5], [2,3,4]]
public class Solution {public List<List<Integer>> combinationSum3(int k, int n) {List<List<Integer>> res=new ArrayList<List<Integer>>();if(n>45 || k>9) return res;List<Integer> temp=new ArrayList<Integer>();select_num(k,1,n, temp, res);return res;}public void select_num(int k,int idx,int n, List<Integer> temp, List<List<Integer>> res){if(n<0) return;if(k==0&& n==0){List<Integer> temp_new=new ArrayList<Integer>(temp);res.add(temp_new);return;}if(idx>9) return;temp.add(idx);select_num(k-1,idx+1,n-idx,temp,res);temp.remove(temp.size()-1);select_num(k,idx+1,n,temp,res);}}[/code]
相关文章推荐
- SQL Server分区键列必须是主键一部分
- JS控制自适应瀑布流
- XenDesktop 7.5 静态组电源管理需要通过命令来管理
- Microsoft.SqlServer.Management.SqlMgmt.SimpleJobSchedule”上的属性访问器“ScheduleRecurrenceAndTimes”发生以下异常:
- 第十三周阅读程序一
- 六.一儿童节快乐!
- 苹果开发小记(一):NSString 的比较用法
- 将Blob类型的字段作为查询条件来进行查询
- 甲骨文中间件:将加大投资 重视潜在用户(2014.4.3)
- Android Activity组件正常以及锁屏状态下的启动流程
- 通过备份初始化合并复制时的报错的解决
- Swift的属性,方法,下标脚本以及继承
- ImageView android:tint
- linux 上安装SVN并导入(个人实操)
- oracle查询用户所在的表空间
- Struts2原理
- 发现数据库错误模式(AppScan扫描结果)
- Thread.sleep还是TimeUnit.SECONDS.sleep
- 限定查询与排序显示(章节摘要)
- Python 反编译工具uncompyle2