• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: Combination Sum

第一次没考虑到要加个系数cur, 因为必须从小到大排序,导致答案里有[1, 2]和[2, 1],加入cur后就acm了

 1 class Solution {
 2 public:
 3     void dfs(vector<int> candidates, int target, int sum, vector<int> &save, vector<vector<int>> &ret, int cur) {
 4         if (sum > target) return;
 5         if (sum == target) {
 6             ret.push_back(save);
 7             return;
 8         }
 9         for (int i = cur; i < candidates.size(); i++) {
10             save.push_back(candidates[i]);
11             dfs(candidates, target, sum+candidates[i], save, ret, i);
12             save.pop_back();
13         }
14     }
15     vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
16         // Start typing your C/C++ solution below
17         // DO NOT write int main() function
18         sort(candidates.begin(), candidates.end());
19         int sum = 0;
20         vector<vector<int>> ret;
21         vector<int> save;
22         if (candidates.size() == 0) return ret;
23         int cur = 0;
24         dfs(candidates, target, sum, save, ret, cur);
25         return ret;
26     }
27 };

 C#: C#有深浅拷贝的问题,这里浅拷贝的话最后的ans就一直是空。。。所以这里需要深拷贝出来。。。C++没有这个问题方便很多

 1 public class Solution {
 2     public List<List<int>> CombinationSum(int[] candidates, int target) {
 3         Array.Sort(candidates);
 4         int sum = 0;
 5         List<List<int>> ans = new List<List<int>>();
 6         List<int> tmp = new List<int>();
 7         if (candidates.Length == 0) return ans;
 8         int dep = 0;
 9         dfs(candidates, target, sum, ref tmp, ref ans, dep);
10         return ans;
11     }
12     void dfs(int[] candidates, int target, int sum, ref List<int> tmp, ref List<List<int>> ans, int dep)
13     {
14         if (sum > target) return;
15         if (sum == target) {
16             List<int> newTmp = new List<int>();
17             for (int i = 0; i < tmp.Count; i++) newTmp.Add(tmp[i]);
18             ans.Add(newTmp);
19             return;
20         }
21         for (int i = dep; i < candidates.Length; i++) {
22             tmp.Add(candidates[i]);
23             dfs(candidates, target, sum + candidates[i], ref tmp, ref ans, i);
24             tmp.RemoveAt(tmp.Count - 1);
25         }
26     }
27 }
View Code

 

posted @ 2013-03-19 11:56  ying_vincent  阅读(139)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3