美文网首页
combinationII(leetcode216)

combinationII(leetcode216)

作者: zhouwaiqiang | 来源:发表于2018-11-25 19:33 被阅读0次

题目

  • 给定一个表示数量的数字k和一个指定数字n,要求找出所有k个数量数字的和为n的组合,k个数字不能重复,数字是由1-9组成
  • 举例:给定k=3, n=7,返回[[1,2,4]],因为1+2+4 = 7 1,2,4是3个数字

解题思路

  • 可以参考39题Combination sum的解法,其实这就是一道递归实现的题
  • 以例题中k为3,n为7来说,我们假设选定了一个数字1,那么我们就需要从剩余的2-9这几个数字中,选出结果,k此时变为2,n变为6,然后重复上述操作,假设我们选定2的时候此时k变为1,n变为4,然后再从3-9中选出合适的数字,此时4选出会使k为0,n为0,就可以加入到结果中,然后我们再依次返回递归遍历剩下的数字找出所有符合结果的即可。
  • 大体思路就是我们从1开始循环遍历选定一个数字加入到temp这个list中
  • 然后将对应的k值和n值减小继续检查到最后结果,如果符合就将temp加入到result中,不符合则返回继续检查后续的数字
  • 因为我们的数字是从1开始从前往后检查不会出现重复的情况
  • leetcode时间1ms

源代码

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> temp = new ArrayList<>();
        combination(result, temp, 1, k, n);
        return result;
    }
    
    private void combination(List<List<Integer>> result, List<Integer> temp, int start, int k, int n) {
        if (k == 0 && n == 0) {
            result.add(new ArrayList<>(temp));
            return;
        }
        if (k == 0) return;//表示次数用完了
        for (int i = start; i <= 9; i++) {
            if (start > n) return;//start > n那么就不满足条件
            temp.add(i);
            combination(result, temp, i+1, k-1, n-i);
            temp.remove(temp.size()-1);
        }
    }
}

相关文章

  • combinationII(leetcode216)

    题目 给定一个表示数量的数字k和一个指定数字n,要求找出所有k个数量数字的和为n的组合,k个数字不能重复,数字是由...

网友评论

      本文标题:combinationII(leetcode216)

      本文链接:https://www.haomeiwen.com/subject/ficmqqtx.html