DayTwentyFive Dp一点点

解决DP问题时,需要先确定初始状态,然后确定如何转移状态,再编程进行求解。

前序遍历的迭代写法

	vector<int> preorderTraversal(TreeNode* root) {
		vector<int> res;
		while (root)
		{
			if (!root->left)
			{
				res.push_back(root->val);
				root = root->right;
			}
			else
			{
				TreeNode* pre = root->left;
				while (pre->right && pre->right != root) pre = pre->right;
				if (pre->right) pre->right = 0, root = root->right;
				else
				{
					pre->right = root;
					res.push_back(root->val);
					root = root->left;
				}
			}
		}
		return res;
	}

使用一个字符减 ‘0’ 可以得到正确的int值。

调用sort函数排序时,可引入以下这样的一个比较函数,从而获得一个字典序的序列

	static bool cmp(int a, int b) {
		auto as = to_string(a), bs = to_string(b);
		return as + bs < bs + as;
	}

善用deque, 可以借此实现栈和队列。

class MyStack {
public:
	deque<int> q;
	/** Initialize your data structure here. */
	MyStack() {

	}

	/** Push element x onto stack. */
	void push(int x) {
		q.push_back(x);
	}

	/** Removes the element on top of the stack and returns that element. */
	int pop() {
		q.pop_back();
		return q.back();
	}

	/** Get the top element. */
	int top() {
		return q.back();
	}

	/** Returns whether the stack is empty. */
	bool empty() {
		return q.empty();
	}
};

class MyQueue {
public:
	deque<int> q;
	/** Initialize your data structure here. */
	MyQueue() {

	}

	/** Push element x to the back of queue. */
	void push(int x) {
		q.push_back(x);
	}

	/** Removes the element from in front of queue and returns that element. */
	int pop() {
		int x = q.back();
		q.pop_back();
		return x;
	}

	/** Get the front element. */
	int peek() {
		return q.front();
	}

	/** Returns whether the queue is empty. */
	bool empty() {
		return q.empty();
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值