Leetcode题解(20)

时间:2023-03-09 07:10:38
Leetcode题解(20)

59. Spiral Matrix II

题目

Leetcode题解(20)

这道题copy网上的代码

 class Solution {
private:
int step[][];
bool canUse[][];
public:
void dfs(int dep, vector<vector<int> > &matrix, int direct, int x, int y)
{
for(int i = ; i < ; i++)
{
int j = (direct + i) % ;
int tx = x + step[j][];
int ty = y + step[j][];
if ( <= tx && tx < matrix.size() && <= ty && ty < matrix[].size() && canUse[tx][ty])
{
canUse[tx][ty] = false;
matrix[tx][ty] = dep;
dfs(dep + , matrix, j, tx, ty);
}
}
} vector<vector<int> > generateMatrix(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
step[][] = ;
step[][] = ;
step[][] = ;
step[][] = ;
step[][] = ;
step[][] = -;
step[][] = -;
step[][] = ;
vector<vector<int> > ret(n, vector<int>(n));
memset(canUse, true, sizeof(canUse));
dfs(, ret, , , -); return ret;
} };

----------------------------------------------------------------------------分割线----------------------------------------------------------------------

60. Permutation Sequence

题目

Leetcode题解(20)

分析:这道题主要考数学推断

在n!个排列中,第一位的元素总是(n-1)!一组出现的,也就说如果p = k / (n-1)!,那么排列的最开始一个元素一定是nums[p]。

假设有n个元素,第K个permutation是
a1, a2, a3, .....   ..., an
那么a1是哪一个数字呢?
那么这里,我们把a1去掉,那么剩下的permutation为
a2, a3, .... .... an, 共计n-1个元素。 n-1个元素共有(n-1)!组排列,那么这里就可以知道
设变量K1 = K
a1 = K1 / (n-1)!
同理,a2的值可以推导为
a2 = K2 / (n-2)!
K2 = K1 % (n-1)!
 .......
a(n-1) = K(n-1) / 1!
K(n-1) = K(n-2) /2!
an = K(n-1)

代码如下:

 class Solution {
public:
string getPermutation(int n, int k) {
vector<int> nums(n);
int pCount = ;
for(int i = ; i < n; ++i) {
nums[i] = i + ;
pCount *= (i + );
} k--;
string res = "";
for(int i = ; i < n; i++) {
pCount = pCount/(n-i);
int selected = k / pCount;
res += ('' + nums[selected]); for(int j = selected; j < n-i-; j++)
nums[j] = nums[j+];
k = k % pCount;
}
return res;
}
};

------------------------------------------------------------------------分割线--------------------------------------------------------------------------

61. Rotate List

题目

Leetcode题解(20)

代码如下:

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
//如果k值大于链表长度应该怎么处理
if(NULL == head)
return NULL;
ListNode* temp = head;
int count = ;
while(temp != NULL)
{
count++;
temp = temp->next;
}
k = k%count;
if(k == )
return head;
ListNode *first,*second;
first = head;
int i=k;
while(i--)
{
//if(NULL == first)
// return NULL;
first = first->next;
}
second = head;
while(first->next != NULL)
{
first = first->next;
second = second->next;
}
temp = head;
head = second->next;
first->next = temp;
second->next = NULL;
return head;
}
};