和爲固定值的所有序列

1.問題描述

   給定一個隨意的向量,找到和爲固定值的所有不同的序列。

   例如:向量10,1,2,7,6,1,5 和爲8

   應該得到序列:

   [1,7]

   [1,2,5]

   [2,6]

   [1,1,6]

   要求:序列中所有值都是整數,輸出元素是從小到大排序的。輸出的集合不能有重複的;

2.解法

   解析:1:因爲要求輸出是排序的,那麼可以首先對序列排序,可以使用快速排序。

               2:排完序後,當遇到數大於和時,就沒與必要再考慮後面的數了,因爲所有的數都是整數.

               3:採用遞歸方法,從第一個數開始,如果包括這個數時,則需要在剩下的所有數當中找和減去剛纔這個數。

                     不包括這個數時,則剩下的所有數中找和的序列,這樣規模也就減小了。

               4:另外找的集合不能包括重複的序列,可以採用set集合。


<span style="font-size:14px;">class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) 
    {
        qsort(candidates,0,candidates.size()-1);
        vector<int>f1;
        combinationSum(candidates,target,f1,0);
        
        set<vector<int>>::iterator iter=ans.begin();
        while(iter!=ans.end())
        {
            res.push_back(*iter);
            iter++;
        }
        
        return res;
    }
    
    void combinationSum(vector<int> &can, int target, vector<int> f1,int begin)
    {
        if( 0 == target )
        {
           // res.push_back(f1);
           ans.insert(f1);
            
        }
        if(target<0 || begin>=can.size() || can[begin]>target)
        { 
            return;  
        }
        if(target>0)
        {
            f1.push_back(can[begin]);
            begin++;
             
            combinationSum(can,target-can[begin-1], f1,begin);
            
            f1.pop_back();
            combinationSum(can,target,f1,begin);
        }
    }
    
    void swap(int *a,int *b)
    {
        int temp=*a;
        *a=*b;
        *b=temp;
    }
    
    int partition(vector<int>& array, int left, int right)
    {
        int pivot = array[right];
        int pos = left-1;
        for(int index = left; index < right; index++)
        {
            if(array[index] <= pivot)
                swap(&array[++pos], &array[index]);
        }
        swap(&array[++pos], &array[right]);
        return pos;//返回 pivot 所在位置
    }
    
    void qsort(vector<int>& can,int begin,int end)
    {
        if(begin<end)
        {
            int mid=partition(can,begin,end);
            qsort(can,begin,mid-1);
            qsort(can,mid+1,end);
        }
    }
    
    private:
      vector<vector<int>> res;
      set<vector<int>> ans;
};</span>


該方法是從遞歸的角度考慮的,編程比較複雜,但是,還有一種比較簡單的解法——回溯法
發佈了42 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章