216. Combination Sum III

February 01, 2017

216. Combination Sum III

Description

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.

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

Analysis

此题和之前的 Combination Sum一样,都是应用回溯法,不过需要加上一个sum参数记录当前的数组中的元素的和,其余没有任何变化。

代码如下:

code

class Solution {
private:
    void backtracking(vector<vector<int>> & res,vector<int> & temp,vector<int> & base,int sum,int start,int k,int n){
        if(sum==n&&temp.size()==k){
            res.push_back(temp);
            return;
        }
        for(int i=start;i<base.size();++i){
            temp.push_back(base[i]);
            backtracking(res,temp,base,sum+base[i],i+1,k,n);
            temp.pop_back();
        }
    }    
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<int> base={1,2,3,4,5,6,7,8,9};
        vector<vector<int>> res;
        vector<int> temp;
        backtracking(res,temp,base,0,0,k,n);
        return res;
    }
};

北邮教务系统评教脚本

Published on September 17, 2017

72.Edit distance

Published on September 17, 2017