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 }
  • 相关阅读:
    Java异常简介
    Java中的接口
    Java中的抽象类
    Java的多态
    关于this
    面向对象的继承方式详解
    1像素边框问题
    HTML5之本地存储SessionStorage
    js数组去重的4个方法
    前端模块化
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6388959.html
Copyright © 2011-2022 走看看