首页 > 其他 > 详细

216. Combination Sum III

时间:2017-02-11 12:48:01      阅读:200      评论:0      收藏:0      [点我收藏+]

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.


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

本题在combination2的基础上,添加了元素个数,比较简单,代码如下:
 1 public class Solution {
 2     public List<List<Integer>> combinationSum3(int k, int n) {
 3         List<List<Integer>> res = new ArrayList<>();
 4         int[] num = new int[]{1,2,3,4,5,6,7,8,9};
 5         backtracking(res,new ArrayList<Integer>(),num,k,n,0);
 6         return res;
 7     }
 8     public void backtracking(List<List<Integer>> res,List<Integer> list,int[] num,int k,int target,int start){
 9         if(list.size()>k) return;
10         if(target<0) return;
11         else if(target==0){
12             if(list.size()==k)
13             res.add(new ArrayList<Integer>(list));
14         }else{
15             for(int i=start;i<num.length;i++){
16                 list.add(num[i]);
17                 backtracking(res,list,num,k,target-num[i],i+1);
18                 list.remove(list.size()-1);
19             }
20         }
21     }
22 }

 

216. Combination Sum III

原文:http://www.cnblogs.com/codeskiller/p/6388959.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!