LeetCode | 52. N-Queens II 经典算法n后问题回溯法

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the totalnumber of distinct solutions.

经典算法值n后问题,

这题题给你一个n*n的棋盘,问你放置n个皇后共有多少种不用的放置方法,

这一一个典型的回溯法框架,并且也是很简单的一个回溯法框架,比这个更简单的就只有字符串全排列问题了。

这题使用深度优先遍历的回溯法解决,每一行只放一个皇后,每一列只放一个皇后,如何判断某个皇后是否和前面已经放置的皇后斜线冲突呢,使用abs(a-b)==abs(c-d),ac,bd分别为参与判断的两个皇后的横纵坐标,只要这个等式成立则这两个皇后一定斜线冲突

class Solution {
public:
int findRadius(vector<int>& houses, vector<int>& heaters) {
	sort(houses.begin(), houses.end());
	sort(heaters.begin(), heaters.end());

	int index = 0; int m = -1;
	for (int i = 0; i < houses.size(); i++)
	{
		while (index < heaters.size()&& heaters[index] < houses[i]) index++;
		if (index == heaters.size()) m = max(m, houses[i] - heaters[index - 1]);
		else if(index==0)
		{
			m = max(m, heaters[0] - houses[i]);
		}
		else
		{
			m = max(m, min(houses[i]-heaters[index-1],heaters[index]-houses[i]));
		}
	}
	return m;
}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值