码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode的medium题集合(C++实现)五

时间:2015-05-16 12:00:54      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:递归   c++   leetcode   

1 Combination Sum
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times.
可以采用递归的方法解决这个问题,当找到一组数之和等于目标后将这组数加入容器,然后返回;当一组数之和大于目标,立即返回;当小于目标继续递归。

void dfscombine(vector<int>& candidates,int level,int& sum,int target,vector<int>& mid,vector<vector<int> >& result)
    {
        if(sum>target) return;
        else if(sum==target)
        {
           result.push_back(mid);
           return;
        }
        else
        {
          for(int i=level;i<candidates.size();i++)
          {
              sum+=candidates[i];
              mid.push_back(candidates[i]);
              dfscombine(candidates,i,sum,target,mid,result);
              mid.pop_back();
              sum-=candidates[i];
          }
        }
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<int> mid;  
        vector<vector<int> > result;  
        sort(candidates.begin(),candidates.end());
        int level=0,sum=0;
        dfscombine(candidates,level,sum,target,mid,result);
        return result;
    }

2 Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. Each number in C may only be used once in the combination.
该题与上一题的区别是给定的数据集中的数据只能用一次,我只需将上题中递归的参数level=i 改为 level=i+1 即可。同时,与前面讲过的3sum等问题类似,防止从容器中pop_back() 出来的数与即将加入容器中的数相等而造成重复。

void dfscombine(vector<int>& candidates,int level,int& sum,int target,vector<int>& mid,vector<vector<int> >& result)
    {
        if(sum>target) return;
        else if(sum==target)
           result.push_back(mid);
        else
        {
          for(int i=level;i<candidates.size();i++)
          {
              sum+=candidates[i];
              mid.push_back(candidates[i]);
              dfscombine(candidates,i+1,sum,target,mid,result); //保证一个元素只用一次
              mid.pop_back();
              sum-=candidates[i];
              while(i<candidates.size()-1 && candidates[i]== candidates[i+1]) i++;  //防止重复
          }
        }
    }
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<int> mid;  
        vector<vector<int> > result;  
        sort(candidates.begin(),candidates.end());
        int level=0,sum=0;
        dfscombine(candidates,level,sum,target,mid,result);
        return result;
    }

LeetCode的medium题集合(C++实现)五

标签:递归   c++   leetcode   

原文地址:http://blog.csdn.net/zhulong890816/article/details/45766469

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!