#90 k Sum II

来源:互联网 发布:python unicode转中文 编辑:程序博客网 时间:2024/05/24 05:29

题目描述:

Given n unique integers, number k (1<=k<=n) and target.

Find all possible k integers where their sum is target.

Example

Given [1,2,3,4], k = 2, target = 5. Return:

[  [1,4],  [2,3]]
题目思路:

这题是比较经典的dfs算法,我的code中用sofar记录下每一次尝试的vector,当sofar满足要求(sofar的所有元素和为target,并且sofar的长度为k)时,sofar就是answer之一。在dfs中,将array A中的每个没被访问到的元素都捡进篮子(sofar)里考虑一遍,如果正好能凑成满足要求的vector,则加入到答案中;否则,如果sofar长度超过k,就不予考虑。这里需要注意的是,为了避免最终结果ans中出现重复答案,需要设置一个searching starting index,这样可以保证dfs一直往后搜索,没有重复搜索。

Mycode (AC = 325ms)

class Solution {public:    /**     * @param A: an integer array.     * @param k: a positive integer (k <= length(A))     * @param target: a integer     * @return a list of lists of integer      */    vector<vector<int> > kSumII(vector<int> A, int k, int target) {        // write your code here        // initialize the vectors        vector<vector<int>> ans;        vector<int> sofar;        vector<bool> visited(A.size(), false);                // call dfs function        kSumIIhelper(ans, sofar, visited, A, k, 0, target);        return ans;    }        // dfs function to find the possible k integers    void kSumIIhelper(vector<vector<int>>& ans, // final answer                      vector<int>& sofar, // vector to store possible integers where their sum is target                      vector<bool>& visited, // indicate which element is visited, to avoid re-selection                      vector<int>& A,                       int k,                       int index, // starting index for searching, to avoid duplicate answers                      int target)    {        if (sofar.size() > k) {            return;        }                // if get the answer        if (sofar.size() == k && target == 0) {            ans.push_back(sofar);            return;        }                // do searching for each unvisited element        for (int i = index; i < A.size(); i++) {            if (!visited[i]) {                visited[i] = true;                sofar.push_back(A[i]);                                kSumIIhelper(ans, sofar, visited, A, k, i + 1, target - A[i]);                                // resume the vectors to be previous, for next searching                visited[i] = false;                sofar.pop_back();            }        }            }};


0 0
原创粉丝点击