zoukankan      html  css  js  c++  java
  • 216. Combination Sum III

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

    本题在combination2的基础上,添加了元素个数,比较简单,代码如下:
     1 public class Solution {
     2     public List<List<Integer>> combinationSum3(int k, int n) {
     3         List<List<Integer>> res = new ArrayList<>();
     4         int[] num = new int[]{1,2,3,4,5,6,7,8,9};
     5         backtracking(res,new ArrayList<Integer>(),num,k,n,0);
     6         return res;
     7     }
     8     public void backtracking(List<List<Integer>> res,List<Integer> list,int[] num,int k,int target,int start){
     9         if(list.size()>k) return;
    10         if(target<0) return;
    11         else if(target==0){
    12             if(list.size()==k)
    13             res.add(new ArrayList<Integer>(list));
    14         }else{
    15             for(int i=start;i<num.length;i++){
    16                 list.add(num[i]);
    17                 backtracking(res,list,num,k,target-num[i],i+1);
    18                 list.remove(list.size()-1);
    19             }
    20         }
    21     }
    22 }
  • 相关阅读:
    Windows10 iis10 arr webfarm
    两个command的疑惑
    关于controller和apicontroller的跨域实现过滤器的不同
    抽象工厂
    c# 字体库跨域解决
    c# 父类的引用指向子类的实例
    垂直居中
    扇形导航
    2D变换
    京东放大镜效果
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6388959.html
Copyright © 2011-2022 走看看