一天一道算法题——216. 组合总和 III

    xiaoxiao2022-07-05  162

    题目描述

    找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。

    说明:

    所有数字都是正整数。 解集不能包含重复的组合。

    示例 1:

    输入: k = 3, n = 7 输出: [[1,2,4]]

    示例 2:

    输入: k = 3, n = 9 输出: [[1,2,6], [1,3,5], [2,3,4]]

    解题思路

    递归回溯

    程序实现

    class Solution { public List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> list = new ArrayList(); add(list,new int[k],0,k,n); return list; } private void add(List<List<Integer>> list, int[] choose,int index,int k, int n){ if(index == k){ int sum = 0; for(int j :choose){ sum += j; } if(sum == n){ List<Integer> result = new ArrayList<Integer>(); for(int j :choose){ result.add(j); } list.add(result); } return; } int start = index == 0 ? 1 : choose[index-1] + 1; for(int i = start;i<10;i++){ choose[index] = i; add(list,choose,index + 1,k,n); } } }
    最新回复(0)