zoukankan      html  css  js  c++  java
  • LC 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.

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

    Runtime: 0 ms, faster than 100.00% of C++ online submissions for Combination Sum III.

    class Solution {
    public:
      vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> ret;
        vector<int> path;
        int target = 0;
        helper(k, n, 0, 0, target, path, ret);
        return ret;
      }
      void helper(const int k ,const int n, int i_th, int prev, int& target, vector<int>& path, vector<vector<int>>& ret){
        if(i_th == k && n == target) {
          ret.push_back(path);
          return ;
        }
        for(int i=prev+1; i < 10; i++){
          path.push_back(i);
          target += i;
          helper(k, n, i_th+1, i, target, path, ret);
          target -= i;
          path.pop_back();
        }
      }
    };
  • 相关阅读:
    使用junit进行单元测试
    初学软件工程.
    初学软件工程
    寻医问药软件
    使用JUnit工具进行单元测试
    软件工程问题
    JUnit进行单元测试
    软件工程学习问题
    单元测试
    软件工程
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10208048.html
Copyright © 2011-2022 走看看