刷题560. Subarray Sum Equals K

一、题目说明

题目560. Subarray Sum Equals K,给一列整数和一个整数k,找到所有子数组和是k的个数。难度是Medium!

二、我的解答

这个题目第一印象是用dp,很快代码就写好了。然而 Memory Limit Exceeded,其中vector<vector<int> > dp(len+1,vector<int>(len+1,0));

代码如下:

class Solution{
	public:
		int subarraySum(vector<int>& nums,int k){
			int len = nums.size();
			int total = 0;
			vector<vector<int> > dp(len+1,vector<int>(len+1,0));
			for(int i=0;i<len;i++){
				dp[i][i] = nums[i];
				if(nums[i]==k){
					total++;
				}
			}
			for(int i=0;i<len;i++){
				for(int j=i+1;j<len;j++){
					dp[i][j] = dp[i][j-1] + nums[j];
					if(dp[i][j]==k){
						total++;
					}
				}
			}
			return total;
		}
};

三、优化措施

那就一个一计算吧,用dfs:

class Solution{
	public:
		int subarraySum(vector<int>& nums,int k){
			int len = nums.size();
			int total = 0;

			for(int i=0;i<len;i++){
				total += dfs(nums,i,k);
			}
			
			return total;
		}
		int dfs(vector<int>& nums,int start,int k){
			int total = 0;
			int sum = 0;
			for(int i=start;i<nums.size();i++){
				sum += nums[i];
				if(sum==k) total++;
			}
			return total;
		}
};

性能如下:

Runtime: 464 ms, faster than 24.82% of C++ online submissions for Subarray Sum Equals K.
Memory Usage: 9.8 MB, less than 98.67% of C++ online submissions for Subarray Sum Equals K.
posted @ 2020-04-28 09:53  siwei718  阅读(100)  评论(0编辑  收藏  举报