当前位置:网站首页>1259. 不相交的握手 動態規劃
1259. 不相交的握手 動態規劃
2022-07-23 18:41:00 【鈺娘娘】
1259. 不相交的握手
偶數 個人站成一個圓,總人數為
num_people。每個人與除自己外的一個人握手,所以總共會有num_people / 2次握手。將握手的人之間連線,請你返回連線不會相交的握手方案數。
由於結果可能會很大,請你返回答案 模
10^9+7後的結果。示例 1:
輸入:num_people = 2 輸出:1示例 2:
輸入:num_people = 4 輸出:2 解釋:總共有兩種方案,第一種方案是 [(1,2),(3,4)] ,第二種方案是 [(2,3),(4,1)] 。示例 3:
輸入:num_people = 6 輸出:5示例 4:
輸入:num_people = 8 輸出:14提示:
2 <= num_people <= 1000num_people % 2 == 0
做題結果
成功,這題大概屬於困難題中特別簡單的
方法:動態規劃
- 假設有 x 個人,我們從中任選了一個人 a,這個 a和一個人握手,要保證後續有解,則分割出的兩部分必須都為偶數
- a 握手以後,還剩下,x-2個人沒握手,x 握手以後,把剩餘人員通過握手的連線分割為兩部分,假設其中一個部分為 y 個人,則剩餘部分為 x-2-y 個人
- 這個 y 人握手問題,就化解為了 x 人握手的子問題,枚舉 所有可行的 y 和 x-2-y 握手可能性,兩者互不幹涉,可相乘處理
優化
- 由於都是偶數,我們只關心有多少對握手,可將空間範圍縮减為 n/2
- 一邊分割為 y 人,一邊分割為 x-2-y 人,與反過來的結果是相同的,那麼對於兩邊數目不同的情况,可以乘以2,從而减少一半循環次數,特別注意的是,當 y=x-2-y時,只有一種可能性,
class Solution {
public int numberOfWays(int numPeople) {
int half = numPeople/2;
long[] dp = new long[half+1];
long MOD = (long) (1e9+7);
dp[0]=1;
for(int i = 1; i <= half; i++){
for(int j = 0; j < i-j-1; j++){
dp[i]+=dp[j]*dp[i-j-1]*2;
dp[i] = dp[i]%MOD;
}
if(i%2!=0){
dp[i]+=dp[i/2]*dp[i-i/2-1];
dp[i] = dp[i]%MOD;
}
}
return (int) dp[half];
}
}時間複雜度:O(n)
空間複雜度:O(n)
边栏推荐
猜你喜欢

【游戏建模模型制作全流程】ZBrush武器模型制作:弩

Paddlenlp之UIE分类模型【以情感倾向分析新闻分类为例】含智能标注方案)

SQLZOO——BBC QUIZ

Jetpack Compose之Navigation组件使用

MySql【从了解到掌握 一篇就够】

多线程【全面学习 图文精讲】

【攻防世界WEB】难度三星9分入门题(终):fakebook、favorite_number

Learn about spark project on nebulagraph

接口测试概述

Is learning next generation modeling a good scene or a good role? Choose the right profession and pay more than half
随机推荐
Boss online replay: the mistake I made when training Dall · e
Three things programmers want to do most | comics
Prevent and control the summer market blowout after adjustment, and evaluate the summer activities of Tujia, muniao and meituan
Modeling just learning is very confused. How to learn the next generation role modeling process?
Stack / heap / queue question brushing (medium)
How does Apache, the world's largest open source foundation, work?
[sharing 3D modeling and production skills] how ZBrush turns pictures into relief models
学次世代建模是场景好还是角色好?选对职业薪资多一半
元胞数组处理
【游戏建模模型制作全流程】ZBrush武器模型制作:弩
【Coggle 30 Days of ML】糖尿病遗传风险检测挑战赛(2)
大神“魔改”AirPods,配备USB-C接口,3D打印外壳让维修更容易
Huawei fat thin AP switching method
UAV circumnavigating an unknown target under a GPS-deniedenvironment with range-only measurements翻译
如何理解:普通代码块、构造块、静态块?有什么关系?
Database modeling
What happened behind kubectl's creation of pod?
[attack and defense world web] difficulty Samsung 9-point introductory question (end): Fakebook, favorite_ number
[jzoof] 13 plage de mouvement du robot
使用kail破解wifi密码

