@LIUHUAN
2019-05-25T16:37:33.000000Z
字数 3295
阅读 742
algorithm
在此输入正文
int minimumTotal(vector<vector<int>>& triangle) {
int m = triangle.size();
if(m <= 0 || triangle[0].size() <=0 )
return 0;
vector<vector<int>> dp;
dp.push_back({triangle[0]});
for(int i = 1; i < m; i++ ) {
int n = triangle[i].size();
dp.push_back(vector<int>(n,0));
for(int j = 0; j < n ; j++){
dp[i][j] = min(getij(dp,i-1,j-1) , getij(dp,i-1,j)) + triangle[i][j];
}
}
int minv = INT_MAX;
for(int j = 0; j < triangle[m-1].size();j++) {
minv = min(dp[m-1][j],minv);
}
return minv;
}
int getij(vector<vector<int>> & m , int i ,int j) {
int n = m.size();
if(n <= 0 || i < 0 || i >= n || j >= m[i].size() || j < 0 )
return INT_MAX;
return m[i][j];
}
bool checkSubarraySum(vector<int>& nums, int k) {
int n = nums.size();
if(n <= 1 )
return 0;
if(k == 0 ) {
for(int i = 1 ;i < n ;i++) {
if(nums[i] == 0 && (nums[i-1] == 0 )) {
return 1;
}
}
return 0;
}
k = abs(k);
vector<vector<int>> dp(n,vector<int>(k,0));
int idx = nums[0] % k;
dp[0][idx] = 1;
for(int i = 1; i < n; i++ ) {
idx = nums[i] % k;
for(int j = 0; j < k; j++ ) {
int t = (j + idx) % k;
if(dp[i-1][j])
dp[i][t] = 1;
}
if(dp[i][0])
return 1;
dp[i][idx] = 1;
}
return 0;
}
map[2] = 1
,下次计算直接模的结果2与当前数的和,并记录在另一个map中。
bool checkSubarraySum(vector<int>& nums, int k) {
int n = nums.size();
if(n <= 1 )
return 0;
if(k == 0 ) {
for(int i = 1 ;i < n ;i++) {
if(nums[i] == 0 && (nums[i-1] == 0 )) {
return 1;
}
}
return 0;
}
k = abs(k);
vector<unordered_map<int,int>> dp(n,unordered_map<int,int>());
int idx = nums[0] % k;
dp[0][idx] = 1;
for(int i = 1; i < n; i++ ) {
for(auto & e : dp[i-1]) {
idx = nums[i] % k;
int t = (e.first + idx) % k;
dp[i][t] = 1;
}
if(dp[i].find(0) != dp[i].end())
return 1;
dp[i][idx] = 1;
}
return 0;
}
int subarrayBitwiseORs(vector<int>& A) {
int n = A.size();
vector<unordered_map<int,int>> dp(n,unordered_map<int,int>());
unordered_map<int,int> umap;
dp[0][A[0]] = 1;
umap[A[0]] = 1;
for(int i = 1; i< n ;i++) {
umap[A[i]] = 1;
for(auto &e : dp[i-1]) {
int t = e.first | A[i];
dp[i][t] = 1;
umap[t] = 1;
}
dp[i][A[i]] = 1;
}
return umap.size();
}