#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
- #90 k Sum II
- Lintcode - k sum II
- [LintCode]k Sum II
- [刷题]k Sum II
- lintcode:k Sum II
- *[Lintcode]k Sum II
- [LintCode]k Sum II
- 90.k Sum II-k数和 II(中等题)
- subsets/subsets II/Partition Equal Subset Sum/Partition to K Equal Sum Subsets
- K sum
- K Sum
- K sum
- K-SUM
- 找出二叉树中和为k的所有路径 Path Sum II
- lintcode- k数和II-90
- 4 sum题解(K sum)
- leecode_18 4Sum (k Sum)
- 【Leetcode】Path Sum II (Sum)
- RTCP TMMBR字段解析
- nginx变量
- .pch文件的作用及常见的一些问题
- java中float的取值范围
- easyUI treeGrid异步加载,前端+后台实现,包括增删改等具体功能
- #90 k Sum II
- centos7安装npm和nodejs
- 线性表基本操作
- 火狐浏览器内容默认样式表
- NYOJ49 开心的小明 DFS/01背包
- CPISI training and certification
- Linux间进程通信方式
- light oj 1094(初学邻接表)
- navicat 快捷键