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.

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

    链接: http://leetcode.com/problems/combination-sum-iii/

    7/16/2017

    这道题目没说清楚,每个combination当中不能有重复的值。

    注意,第18行可以改为for (int i = pos; i <= 9; i++)并把pos当作递归的一个值,这样每一步可以减少很多比较

     1 public class Solution {
     2     public List<List<Integer>> combinationSum3(int k, int n) {
     3         List<List<Integer>> result = new ArrayList<>();
     4         if (n / k > 9 || n / k < 1) {
     5             return result;
     6         }
     7         List<Integer> combination = new ArrayList<>();
     8         combinationSum(result, k, n, combination);
     9         return result;
    10     }
    11     
    12     private void combinationSum(List<List<Integer>> result, int k, int n, List<Integer> combination) {
    13         if (k == 0 && n == 0) {
    14             result.add(new ArrayList<>(combination));
    15             return;
    16         }
    17         if (n < 0 || k < 0) return;
    18         for (int i = 1; i <= 9; i++) {
    19             if (combination.size() > 0 && i <= combination.get(combination.size() - 1)) continue;
    20             combination.add(i);
    21             combinationSum(result, k - 1, n - i, combination);
    22             combination.remove(combination.size() - 1);
    23         }
    24     }
    25 }

    别人的答案

    http://www.cnblogs.com/yrbbest/p/4982868.html

    更多讨论

    https://discuss.leetcode.com/category/224/combination-sum-iii

  • 相关阅读:
    凸包模板
    1060E Sergey and Subway(思维题,dfs)
    1060D Social Circles(贪心)
    D
    牛客国庆集训派对Day2
    网络流
    Tarjan算法(缩点)
    莫队分块算法
    计算几何
    hdu5943素数间隙与二分匹配
  • 原文地址:https://www.cnblogs.com/panini/p/7193378.html
Copyright © 2011-2022 走看看