leetcode 216. Combination Sum III

来源:互联网 发布:无法连接steam网络 编辑:程序博客网 时间:2024/06/06 20:14

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

我使用num[k]数组来装每次候选的k个数,从1~9中选择是把小的数先选择,这样之后选择的数都要比之前选择的数要大,所以需要usedLow来记录已选择的数中最大的那个,从它+1开始找下一个被选择的数。

package leetcode;import java.util.ArrayList;import java.util.List;public class Combination_Sum_III_216 {List<List<Integer>> result=new ArrayList<List<Integer>>();int theK;public List<List<Integer>> combinationSum3(int k, int n) {theK=k;int[] num=new int[k+1];combination(num, 0, k, n);return result;}public void combination(int[] num,int usedLow,int k,int n){if(k==1){if(n>usedLow&&n<=9){num[k]=n;addToList(num);}return;}for(int i=usedLow+1;i<=9;i++){num[k]=i;combination(num, i, k-1, n-i);}}public void addToList(int[] num){List<Integer> list=new ArrayList<Integer>();int k=theK;while(k>=1){list.add(num[k]);k--;}result.add(list);}public static void main(String[] args) {// TODO Auto-generated method stubCombination_Sum_III_216 c=new Combination_Sum_III_216();List<List<Integer>> result=c.combinationSum3(2, 18);for(List<Integer> list:result){for(Integer i:list){System.out.print(i+" ");}System.out.println();}}}
我看了下,大神的解法思路都跟我一样,好自豪哈哈!

public List<List<Integer>> combinationSum3(int k, int n) {    List<List<Integer>> ans = new ArrayList<>();    combination(ans, new ArrayList<Integer>(), k, 1, n);    return ans;}private void combination(List<List<Integer>> ans, List<Integer> comb, int k,  int start, int n) {if (comb.size() == k && n == 0) {List<Integer> li = new ArrayList<Integer>(comb);ans.add(li);return;}for (int i = start; i <= 9; i++) {comb.add(i);combination(ans, comb, k, i+1, n-i);comb.remove(comb.size() - 1);}}

原创粉丝点击