Leetcode|Combination Sum III[回溯]

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mike_learns_to_rock/article/details/47210645

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]]
解法1: 4ms

class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<int> candidates={1,2,3,4,5,6,7,8,9};
        vector<int> temp;
        vector<vector<int>> res;
        combinationSum(candidates,0,n,temp,res,k);
        return res;
    }

    void combinationSum(vector<int>& candidates,int index,int target,vector<int> temp,vector<vector<int>> &res, int k){
        if(index==candidates.size()||candidates[index]>target||temp.size()>=k) return;//终止条件
        temp.push_back(candidates[index]);
        if(candidates[index]==target&&temp.size()==k){
            res.push_back(temp);//找到一组满足条件的 
            return;
        }
         combinationSum(candidates,index+1,target-candidates[index],temp,res,k);
         temp.pop_back();
         combinationSum(candidates,index+1,target,temp,res,k);
    }
};

解法2:0ms 加个for循环协助递归。

class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<int> candidates={1,2,3,4,5,6,7,8,9};
        vector<int> temp;
        vector<vector<int>> res;
        combinationSum(candidates,0,n,temp,res,k);
        return res;
    }

    void combinationSum(vector<int>& candidates,int index,int target,vector<int> temp,vector<vector<int>> &res, int k){
        if(index==candidates.size()||candidates[index]>target||temp.size()>=k) return;//终止条件
        for(int i=index;i<candidates.size();i++){
          temp.push_back(candidates[i]);
          if(candidates[i]==target&&temp.size()==k){
              res.push_back(temp);//找到一组满足条件的 
              return;
          }
           combinationSum(candidates,i+1,target-candidates[i],temp,res,k);
           temp.pop_back();
        }
           //combinationSum(candidates,index+1,target,temp,res,k);
    }
};

猜你喜欢

转载自blog.csdn.net/mike_learns_to_rock/article/details/47210645