[关闭]
@LIUHUAN 2019-05-25T16:37:33.000000Z 字数 3295 阅读 742

数学相关动态规划

algorithm


在此输入正文

三角形之和

思路1


- 初始条件:

  1. int minimumTotal(vector<vector<int>>& triangle) {
  2. int m = triangle.size();
  3. if(m <= 0 || triangle[0].size() <=0 )
  4. return 0;
  5. vector<vector<int>> dp;
  6. dp.push_back({triangle[0]});
  7. for(int i = 1; i < m; i++ ) {
  8. int n = triangle[i].size();
  9. dp.push_back(vector<int>(n,0));
  10. for(int j = 0; j < n ; j++){
  11. dp[i][j] = min(getij(dp,i-1,j-1) , getij(dp,i-1,j)) + triangle[i][j];
  12. }
  13. }
  14. int minv = INT_MAX;
  15. for(int j = 0; j < triangle[m-1].size();j++) {
  16. minv = min(dp[m-1][j],minv);
  17. }
  18. return minv;
  19. }
  20. int getij(vector<vector<int>> & m , int i ,int j) {
  21. int n = m.size();
  22. if(n <= 0 || i < 0 || i >= n || j >= m[i].size() || j < 0 )
  23. return INT_MAX;
  24. return m[i][j];
  25. }

连续子数组的和为k的倍数

思路1


- 初始情况:

  1. bool checkSubarraySum(vector<int>& nums, int k) {
  2. int n = nums.size();
  3. if(n <= 1 )
  4. return 0;
  5. if(k == 0 ) {
  6. for(int i = 1 ;i < n ;i++) {
  7. if(nums[i] == 0 && (nums[i-1] == 0 )) {
  8. return 1;
  9. }
  10. }
  11. return 0;
  12. }
  13. k = abs(k);
  14. vector<vector<int>> dp(n,vector<int>(k,0));
  15. int idx = nums[0] % k;
  16. dp[0][idx] = 1;
  17. for(int i = 1; i < n; i++ ) {
  18. idx = nums[i] % k;
  19. for(int j = 0; j < k; j++ ) {
  20. int t = (j + idx) % k;
  21. if(dp[i-1][j])
  22. dp[i][t] = 1;
  23. }
  24. if(dp[i][0])
  25. return 1;
  26. dp[i][idx] = 1;
  27. }
  28. return 0;
  29. }

思路2

  1. bool checkSubarraySum(vector<int>& nums, int k) {
  2. int n = nums.size();
  3. if(n <= 1 )
  4. return 0;
  5. if(k == 0 ) {
  6. for(int i = 1 ;i < n ;i++) {
  7. if(nums[i] == 0 && (nums[i-1] == 0 )) {
  8. return 1;
  9. }
  10. }
  11. return 0;
  12. }
  13. k = abs(k);
  14. vector<unordered_map<int,int>> dp(n,unordered_map<int,int>());
  15. int idx = nums[0] % k;
  16. dp[0][idx] = 1;
  17. for(int i = 1; i < n; i++ ) {
  18. for(auto & e : dp[i-1]) {
  19. idx = nums[i] % k;
  20. int t = (e.first + idx) % k;
  21. dp[i][t] = 1;
  22. }
  23. if(dp[i].find(0) != dp[i].end())
  24. return 1;
  25. dp[i][idx] = 1;
  26. }
  27. return 0;
  28. }

连续子数组或结果的个数

  1. int subarrayBitwiseORs(vector<int>& A) {
  2. int n = A.size();
  3. vector<unordered_map<int,int>> dp(n,unordered_map<int,int>());
  4. unordered_map<int,int> umap;
  5. dp[0][A[0]] = 1;
  6. umap[A[0]] = 1;
  7. for(int i = 1; i< n ;i++) {
  8. umap[A[i]] = 1;
  9. for(auto &e : dp[i-1]) {
  10. int t = e.first | A[i];
  11. dp[i][t] = 1;
  12. umap[t] = 1;
  13. }
  14. dp[i][A[i]] = 1;
  15. }
  16. return umap.size();
  17. }

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注