2019/10/13 leetcode周赛

只做出了2题,第三题动态规划根本没思路,菜死了

第三题、掷骰子模拟

 1 int dieSimulator(int n, vector<int>& rollMax) {
 2     vectorint>>> dp(n + 1, vectorint>>(6, vector<int>(16, 0)));
 3     int mod = 7 + 1e9;
 4     for (int i = 0; i < 6; i++)
 5         dp[0][i][1] = 1;
 6     for (int i = 1; i < n; i++)
 7     {
 8         for (int j = 0; j < 6; j++)
 9         {
10             for (int k = 0; k < 6; k++)
11             {
12                 if (j != k)
13                 {
14                     for (int l = 1; l <= rollMax[k]; l++)
15                     {
16                         dp[i][j][1] += dp[i - 1][k][l];
17                         dp[i][j][1] %= mod;
18                     }
19                 }
20                 else
21                 {
22                     for (int l = 1; l < rollMax[k]; l++)
23                     {
24                         dp[i][j][l + 1] += dp[i - 1][k][l];
25                         dp[i][j][l + 1] %= mod;
26                     }
27                 }
28             }
29         }
30     }
31     int res = 0;
32     for (int i = 0; i < 6; i++)
33     {
34         for (int j = 1; j < rollMax[i]; j++)
35         {
36             res += dp[n - 1][i][j];
37             res %= mod;
38         }
39     }
40     return res;
41 }

 第二题贪心

 1 vectorint>> queensAttacktheKing(vectorint>>& queens, vector<int>& king) {
 2     vector<int> a = { 0,-1,-1,-1,0,1,1,1 };
 3     vector<int> b = { -1,-1,0,1,1,1,0,-1 };
 4     int kingrow = king[0];
 5     int kingcol = king[1];
 6     vectorint>> res;
 7     for (int i = 0; i < a.size(); i++)
 8     {
 9         for (int j = 1; j <= 8; j++)
10         {
11             bool ok = false;
12             int x = kingrow + a[i]*j;
13             int y = kingcol + b[i]*j;
14             if (x < 0 || x>8 || y < 0 || y>8)
15                 continue;
16             for (int k = 0; k < queens.size(); k++)
17             {
18                 if (x == queens[k][0] && y == queens[k][1])
19                 {
20                     res.push_back(queens[k]);
21                     ok = true;
22                     break;
23                 }
24             }
25             if (ok)
26                 break;
27         }
28     }
29     return res;
30 }

 

你可能感兴趣的:(2019/10/13 leetcode周赛)