C++ leetcode note

本文探讨了C++中的动态规划技术,包括使用全局变量、局部引用和LRU缓存来优化内存使用。通过实例展示了如何在sort、memoization和bisection中避免数组越界问题,并创建新的向量进行排序。特别关注了如何在solve函数中利用递归和缓存提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. indexing out of vector size might not throw any error but return a number,
  2. C++ STL
    Sort: inplace sort. You’d better create a new vector for sorting.
// sorted is a vector, and will be changed in place after the below call
sort(sorted.begin(),sorted.end());

Swap:

swap(temp[lind],temp[i]);

Bisection: with a sorted vector, you can use lower_bound

int lind=lower_bound(sorted.begin(),sorted.end(),temp[i])-sorted.begin();
  1. Dynamic Programming:
    Memoization: You can use a reference to the dp matrix in the argument, or create a global variable, or create a map as LRU_cache.
    (In python, you can also do them, or even use a LRU_cache package)
// Global Variable defined as the class variable
// initialize to -1, or use memset to set it to something else
int dp[MAXN];
 
// this function returns the number of
// arrangements to form 'n'
int solve(int n)
{
  // base case
  if (n < 0) 
      return 0;
  if (n == 0)
      return 1;
 
  // checking if already calculated
  if (dp[n]!=-1)
      return dp[n];
 
  // storing the result and returning
  return dp[n] = solve(n-1) + solve(n-3) + solve(n-5);
}

// ****************************************
// a dict as LRU_cache

// this function returns the number of
// arrangements to form 'n'
int solve(int n, unordered_map<int,int>& LRU)
{
  // base case
  if (n < 0) 
      return 0;
  if (n == 0)
      return 1;
 
  // checking if already calculated
  if (LRU.find(n) != LRU.end())
      return LRU[n];
 
  // storing the result and returning
  return LRU[n] = solve(n-1) + solve(n-3) + solve(n-5);
}

// ****************************************
// Use a reference to the dp matrix
int solve(int n, vector<int> & dp)
{
  // base case
  if (n < 0) 
      return 0;
  if (n == 0)
      return 1;
 
  // checking if already calculated
  if (dp[n]!=-1)
      return dp[n];
 
  // storing the result and returning
  return dp[n] = solve(n-1) + solve(n-3) + solve(n-5);
}

  1. Memset
memset(t, -1, sizeof(t));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值