LintCode --- k数和II

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/u012319493/article/details/80993105

Given n unique integers, number k (1<=k<=n) and target.
Find all possible k integers where their sum is target.
样例
给出[1,2,3,4],k=2, target=5,返回 [[1,4],[2,3]]

class Solution {
public:
    /*
     * @param A: an integer array
     * @param k: a postive integer <= length(A)
     * @param target: an integer
     * @return: A list of lists of integer
     */

    void dfs(int dep, int sum, int kk, vector<vector<int>> &ans, vector<int> tmp, vector<int> &A, int k, int targer)
    {
        if(kk == k && sum == targer)
        {
            ans.push_back(tmp);
            return;  // !
        }
        if(sum > targer || dep >= A.size())
            return;

        tmp.push_back(A[dep]);
        dfs(dep+1, sum+A[dep], kk+1, ans, tmp, A, k, targer);
        tmp.pop_back();
        dfs(dep+1, sum, kk, ans, tmp, A, k, targer);
    }

    vector<vector<int>> kSumII(vector<int> &A, int k, int targer) {
        // write your code here
        vector<vector<int>> ans;
        vector<int> tmp;

        dfs(0, 0, 0, ans, tmp, A, k, targer);
        return ans;

    }
};
阅读更多

没有更多推荐了,返回首页