216. Combination Sum III

Total Accepted: 26890  Total Submissions: 77419  Difficulty: Medium

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags
  Array Backtracking
Hide Similar Problems
  (M) Combination Sum

分析:

本题和<LeetCode OJ> 77. Combinations基本一样,利用回溯法找到所有组合情况,并且求和。

主要区别就在于获取答案时不但要满足指定的数组长度,而且还要满足指定的和

本题联动:

<LeetCode OJ> 77. Combinations

<LeetCode OJ> 78 / 90 Subsets (I / II)

<LeetCode OJ> 39./40 Combination Sum(I / II)

class Solution {
public:
    void dfs(vector<int> &subres,int curSum,int start, int target)//使用引用,有利于防止内存大爆炸    
    {    
        if (subres.size()==nsize && curSum == target)//显然此时要满足两个条件才能获得答案,并且回溯    
        {    
            result.push_back(subres);     
            return;   
        }
        
        for (int i = start; i <= 9; i++)    
        {    
            if(i > target || (curSum+i) > target)//此种情况即可回溯
                return;
            subres.push_back(i);
            dfs(subres,curSum+i,i + 1,target);//执行一个深度上的组合,并计算和。计算和时一定要这样计算(可以保留本层的sum)
            subres.pop_back(); //每当执行完一个深度上的组合就弹掉末尾元素 ,准备下一轮回溯寻找组合
        }    
    } 
    vector<vector<int>> combinationSum3(int k, int n) {
        if ( k == 0)     
            return result;   
        nsize=k;    
        vector<int> subres;    
        dfs(subres,0,1,n);    
        return result;   
    }
private:  
    vector<vector<int > > result;  
    int nsize;
};





注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50849690

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

你可能感兴趣的:(LeetCode,C++,面试,动态规划,回溯法)