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

    1. Title

    Combination Sum III

    2. Http address

    https://leetcode.com/problems/combination-sum-iii/

    3. The question

    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.

    Ensure that numbers within the set are sorted in ascending order.


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

    4. My code(AC)

     1     // Accepted
     2       public List<List<Integer>> combinationSum3(int k, int n) {
     3             
     4           List<List<Integer>> result = new ArrayList<List<Integer>>();
     5           getNumber(1, k , n, new ArrayList<Integer>(), result);
     6           return result;
     7         }
     8       
     9       public void getNumber(int begin, int k , int n, ArrayList<Integer> subList, List<List<Integer>> result)
    10       {
    11         int len = subList.size();
    12         int sum = 0;
    13         if( len == k )
    14         {
    15             for(int i = 0 ; i < len ; i++)
    16             {
    17                 sum += subList.get(i);
    18             }
    19             if( sum == n)
    20             {
    21                 result.add(new ArrayList<Integer>(subList));
    22             }
    23             return;
    24         }
    25         
    26         for(int i = begin ; i <= 9 ; i++)
    27         {
    28             subList.add(i);
    29             getNumber(i + 1, k, n, subList, result);
    30             subList.remove(subList.size() - 1);
    31         }
    32       }
  • 相关阅读:
    详解 Android Activity 生命周期
    设计模式:装饰者模式
    析构函数virtual与非virtual区别 [转]
    详解 常量指针和指针常量
    [转]Python yield 使用浅析
    python 列表 总结
    [转]关于Python中的yield
    详解c++指针的指针和指针的引用
    转:Ogre源码剖析
    转:Ogre源码剖析1
  • 原文地址:https://www.cnblogs.com/ordili/p/4969992.html
Copyright © 2011-2022 走看看