Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a00617f

Browse files
author
fupengfei
committed
01/23 COMMIT
1 parent c7fd1d7 commit a00617f

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

‎Leetcode/59. Spiral Matrix II.cpp‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*Spiral Matrix II:Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.*/
2+
class Solution {
3+
public:
4+
vector<vector<int>> generateMatrix(int n) {
5+
vector<vector<int> > matrix(n,vector<int>(n,0));
6+
if(n <= 0){
7+
return matrix;
8+
}
9+
int count = n * n;
10+
int index = 1;
11+
int x = 0,y = -1;
12+
while(index <= count){
13+
// right
14+
++y;
15+
while(y < n && matrix[x][y] == 0){
16+
matrix[x][y++] = index;
17+
++index;
18+
}
19+
--y;
20+
// down
21+
++x;
22+
while(x < n && matrix[x][y] == 0){
23+
matrix[x++][y] = index;
24+
++index;
25+
}
26+
--x;
27+
// left
28+
--y;
29+
while(y >= 0 && matrix[x][y] == 0){
30+
matrix[x][y--] = index;
31+
++index;
32+
}
33+
++y;
34+
// up
35+
--x;
36+
while(x >= 0 && matrix[x][y] == 0){
37+
matrix[x--][y] = index;
38+
++index;
39+
}
40+
++x;
41+
}
42+
return matrix;
43+
}
44+
};
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*Permutation Sequence:Given n and k, return the kth permutation sequence.*/
2+
class Solution {
3+
public:
4+
string getPermutation(int n, int k) {
5+
--k;
6+
string s;
7+
string res;
8+
int i;
9+
int fac = 1;
10+
for (i = 1; i <= n; ++i) {
11+
s.push_back(i + '0');
12+
fac *= i;
13+
}
14+
15+
int cnt;
16+
int idx;
17+
18+
cnt = n;
19+
while (s.size() > 0) {
20+
fac /= cnt--;
21+
idx = k / fac;
22+
k %= fac;
23+
res.push_back(s[idx]);
24+
for (i = idx; i < s.size() - 1; ++i) {
25+
s[i] = s[i + 1];
26+
}
27+
s.pop_back();
28+
}
29+
return res;
30+
}
31+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /