红桃J

用心写好每行完美的代码,远比写一堆更有价值

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

这个题目其实和之前的没有什么区别,只是添加了21到29这一段更新i的代码。这个题目是说在之前题目的基础上允许candidates集合有相同的元素,那么该剔除相同元素的关键在于发现是什么产生了相同的元素。在回溯时如果我们加入了数字a,最后在退出a的时候,如果下一个数字还是a,那么我把它加进去显然这个子树和之前的a并没有什么区别,所以这个时候通过21~29这段代码找到下一个不是a的就可以保证不相同了。

代码:

 1 #include<iostream>
 2 #include<vector>
 3 #include<algorithm>
 4 #define PB push_back
 5 
 6 using namespace std;
 7 
 8 void dfs(vector<int> &num, int index, int sum, int target, vector<vector<int>> &result, vector<int> &combination)
 9 {
10     if (sum == target)
11         result.PB(combination);
12     if (sum > target||index>=num.size())
13         return;
14     for (int i = index; i < num.size();)
15     {
16         combination.PB(num[i]);
17         dfs(num, i + 1, sum + num[i], target, result, combination);
18         combination.pop_back();
19         if (sum + num[i] > target)
20             return;
21         int j = i + 1;
22         while (j<num.size())
23         {
24             if (num[j] == num[i])
25                 j++;
26             else
27                 break;
28         }
29         i = j;
30     }
31 }
32 
33 vector<vector<int>> combinationSum2(vector<int>& candidates, int target) 
34 {
35     sort(candidates.begin(), candidates.end());
36     vector<vector<int>> result;
37     vector<int> combination;
38     dfs(candidates, 0, 0, target, result, combination);
39     return result;
40 }
41 
42 
43 int main()
44 {
45     vector<int> num = { 10, 1, 2, 7, 6, 1, 5 };
46     vector<vector<int>> result = combinationSum2(num, 8);
47     for (int i = 0; i < result.size(); i++)
48     {
49         for (int j = 0; j < result[i].size(); j++)
50             cout << result[i][j] << "    ";
51         cout << endl;
52     }
53 }

 下面是排列组合的思想:

#include<iostream>
#include<vector>
#define VV vector<vector<int>> 
using namespace std;

VV  result;
vector<int>  candidate;

void Permutations(vector<int> nums, vector<int> &can, vector<vector<int>> &result)
{
    if (nums.size() == 0)
        return;
    if (can.size() == 0)
    {
        can.push_back(nums[0]);
    }
    if (can.size() == nums.size())
    {
        result.push_back(candidate);
        return;
    }
    int t = can.size();
    int i = 0;
    while (i <= t)
    {
        can.insert(can.begin() + i, nums[t]);
        Permutations(nums, can, result);
        can.erase(can.begin() + i);
        i++;
    }
}

vector<vector<int>> permute(vector<int>& nums)
{
    Permutations(nums, candidate, result);
    return result;
}

int main()
{
    vector<int> a = {1, 2, 3 };
    Permutations(a, candidate, result);
    for (int i = 0; i < result.size(); i++)
    {
        for (int j = 0; j < result[i].size(); j++)
            cout << result[i][j] << "    ";
        cout << endl;
    }
}
View Code

 

posted on 2015-05-15 10:53  红桃J  阅读(139)  评论(0编辑  收藏  举报