zoukankan      html  css  js  c++  java
  • 0216. Combination Sum III (M)

    Combination Sum III (M)

    题目

    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.

    Note:

    • All numbers will be positive integers.
    • The solution set must not contain duplicate combinations.

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

    题意

    从1-9这9个数中选取k个数,使其之和正好为n,求出所有这样的组合。

    思路

    排列组合题,使用回溯法很容易求解。


    代码实现

    Java

    class Solution {
        public List<List<Integer>> combinationSum3(int k, int n) {
            List<List<Integer>> ans = new ArrayList<>();
            dfs(n, k, 0, 1, new ArrayList<>(), ans);
            return ans;
        }
    
        private void dfs(int n, int k, int sum, int start, List<Integer> temp, List<List<Integer>> ans) {
            if (temp.size() == k && sum == n) {
                ans.add(new ArrayList<>(temp));
                return;
            }
          
            if (temp.size() >= k || sum >= n) {
                return;
            }
          
            for (int i = start; i <= 9; i++) {
                temp.add(i);
                dfs(n, k, sum + i, i + 1, temp, ans);
                temp.remove(temp.size() - 1);
            }
        }
    }
    

    JavaScript

    /**
     * @param {number} k
     * @param {number} n
     * @return {number[][]}
     */
    var combinationSum3 = function (k, n) {
      let ans = []
      dfs(0, [], 1, ans, k, n)
      return ans
    }
    
    let dfs = function (sum, tmp, begin, ans, k, n) {
      if (tmp.length === k && sum === n) {
        return ans.push([...tmp])
      }
    
      if (tmp.length >= k || sum >= n) {
        return
      }
    
      for (let i = begin; i <= 9; i++) {
        tmp.push(i)
        dfs(sum + i, tmp, i + 1, ans, k, n)
        tmp.pop()
      }
    }
    
  • 相关阅读:
    python操作json来存储简单的数据,pickle来操作复杂的数据
    python元组,列表,字典练习
    python文件实现增删改查操作
    socket模拟服务器,客户端下载东西(ftp)
    optiontransferselect标签
    doubleselect标签联动选择框
    datetimepicker标签日期选择器
    combobox标签复合框
    checkboxlist标签多选框组
    使用动态数据的autocomplete标签
  • 原文地址:https://www.cnblogs.com/mapoos/p/13660382.html
Copyright © 2011-2022 走看看