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 }
  • 相关阅读:
    test
    设置section的距离
    UISearchBar的应用
    Centos6.6 系统优化
    Linux系统之间文件传输 scp 命令
    MySQL 数据库安装
    AWS中国EC2 公网IP登录免pemKEY修改shh 配置文件
    Ubuntu 16.04 Chrome浏览器安装flash player插件
    Centos6.6 yum源更新
    qume-kvm 命令管理
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6388959.html
Copyright © 2011-2022 走看看