LeetCode 216. Combination Sum III C++

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

Approach

  1. 这道题也是很经典的递归回溯题,给你一个数n,要求你找有k个元素的组合等于n,组内的元素唯一,组合也唯一。因为是递归回溯,所以我们首先要清楚递归边界和递归式,然后还要选择什么返回值,用来参考是否要回溯。我选的返回值是bool,用来判断当选择这个数的时候,后序是否能成功组合,如果不能,就移除这个数,递归边界就是当这个组合元素数量达到k个,此时要判断组合内元素合是否为n。递归式就是循环判断pos~9这个区间,pos是不断加一,因为题目要有要求元素唯一,所以我传一个pos值,不断加一,缩小区间,避免重复。0ms

Code

class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> ans;
        combination(ans, vector<int>(), 1, n, k, 0);
        return ans;
    }
    bool combination(vector<vector<int>> &ans,vector<int> nums,int pos,int n,int k,int sum) {
        if (sum == k) {
            if (n == 0) {
                ans.push_back(nums);
                return true;
            }
            else {
                return false;
            }
        }
        for (int i = pos; i <= 9; i++) {
            if (n - i >= 0) {
                nums.push_back(i);
                if (!combination(ans, nums, i + 1, n - i, k, sum + 1)) {
                    nums.pop_back();
                }
            }
        }
        return false;
    }
};

你可能感兴趣的:(LeetCode 216. Combination Sum III C++)