Combination Sum [LeetCode]

Problem Description: http://oj.leetcode.com/problems/combination-sum/    

Basic idea: It seems complicate at first. But once I got the recursive idea, the solution was neat. This code could be not efficient. I will rewrite with dynamic programming next time.

 1 class Solution {

 2 public:

 3     vector<vector<int> > combinationSum(vector<int> &candidates, int target) {

 4         // Note: The Solution object is instantiated only once and is reused by each test case.

 5         std::sort(candidates.begin(), candidates.end());

 6         vector<vector<int> > combinations;

 7         for(int i = 0; i < candidates.size(); i ++) {

 8             if(candidates[i] > target)

 9                 break;

10             if(candidates[i] == target) {

11                 vector<int> combination;

12                 combination.push_back(candidates[i]);

13                 combinations.push_back(combination);

14             }else{

15                 if(i == 0 && target % candidates[i] != 0)

16                     continue;

17                 if(i == 0 && target % candidates[i] == 0){

18                     vector<int> combination(target / candidates[i], candidates[i]);

19                     combinations.push_back(combination);

20                     continue;

21                 }

22                 vector<int> sub_candidates(candidates.begin(), candidates.begin() + i + 1);

23                 vector<vector<int> > rests =  combinationSum(sub_candidates, target - candidates[i]);

25                 for(auto item: rests){

26                     item.push_back(candidates[i]);

27                     combinations.push_back(item);

28                 }

30             }

31         }

32         return combinations;

33     }

34 };

你可能感兴趣的:(LeetCode)