Combination Sum III

来源:互联网 发布:ubuntu安装fcitx五笔 编辑:程序博客网 时间:2024/04/30 22:46

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

题目的意思是从1-9中选择k个数字之和是n的组合。与之前的Combination Sum相比

要加入对size是k的判断。

public static List<List<Integer>> combinationSum3(int k, int n) {List<List<Integer>> result = new ArrayList<List<Integer>>();List<Integer> current = new ArrayList<Integer>();combinationSum3(k,n,1,result,current);return result;}public static void combinationSum3(int k,int sum,int start,List<List<Integer>> result,List<Integer> cur){if(sum==0&&cur.size()==k){List<Integer> t=new ArrayList<Integer>(cur);result.add(t);}for(int i=start;i<=9;i++){if(sum-i<0)break;if(cur.size()>k)break;cur.add(i);combinationSum3(k,sum-i,i+1,result,cur);cur.remove(cur.size()-1);}}

0 0