您的位置:首页 > 编程语言 > Java开发

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程序如下:

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: