题目:
Jump Game II
地址:http://oj.leetcode.com/problems/jump-game-ii/
分析:O(n)就可以。DP问题。
代码:
(Python版)
class Solution:
# @param A, a list of integers
# @return an integer
def jump(self, A):
l1 = len(A)
right = A[0]
if l1 == 1:return 0
if right >= l1-1: return 1
if right == 0: ans = 0
else: ans = 1
maxnum = 0
i = 1
while i < l1:
if i <= right:
if i+A[i] > maxnum:
maxnum = i+A[i]
i += 1
else:
if maxnum == right: right += 1
else: right = maxnum
maxnum = 0
ans += 1
if right >= l1-1:
return ans
第二题:
Combinations
地址:http://oj.leetcode.com/problems/combinations/
分析:排列问题,DFS
代码:
(C++版)
class Solution
{
public:
int arr[1000];
int visit[1000];
int ar[1000];
int K;
int N;
vector<vector<int>> ans;
void dfs(int count, int pos)
{
int i;
if(count > K)
{
vector<int> add;
for(i = 1; i < count; i++)
add.push_back(ar[i]);
ans.push_back(add);
return ;
}
for(i = pos; i <= N; i++)
{
if(visit[i] == 0)
{
visit[i] = 1;
ar[count] = i;
dfs(count+1, i+1);
visit[i] = 0;
}
}
}
vector<vector<int> > combine(int n, int k)
{
int i;
for(i = 0; i < 1000; i++) arr[i] = i;
for(i = 0; i < 1000; i++) visit[i] = 0;
K = k;
N = n;
dfs(1,1);
return ans;
}
};
第三题:
Swap Nodes in Pairs
地址:http://oj.leetcode.com/problems/swap-nodes-in-pairs/
分析:指针题,指针用的不熟练,有点DT。。。
代码:
(C++版)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *swapPairs(ListNode *head)
{
int i;
int flag = 0;
if(head == NULL) return head;
ListNode *go, *ans, *pre;
ans = (ListNode *)malloc(sizeof(ListNode));
ans->next = head;
pre = ans;
while(head != NULL)
{
if(head->next != NULL)
{
go = head->next->next;
head->next->next = head;
pre->next = head->next;
head->next = go;
pre = head;
head = go;
}
else break;
}
return ans->next;
}
};
第四题:
Remove Duplicates from Sorted List
地址:http://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/
分析:指针链表的应用,基础题。注意最后head->next = NULL;
代码:
(C++版)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode *deleteDuplicates(ListNode *head)
{
if(head == NULL) return NULL;
ListNode *ans, *go;
ans = (ListNode *)malloc(sizeof(ListNode));
ans->next = head;
go = head->next;
if(go == NULL) return ans->next;
while(go != NULL)
{
if(head->val == go->val)
go = go->next;
else
{
head->next = go;
head = head->next;
go = go->next;
}
}
head->next = NULL;
return ans->next;
}
};
第五题:
Two Sum
地址:http://oj.leetcode.com/problems/two-sum/
分析:记录下index,把value排序,然后利用two pointers就OK了。
代码:
(C++版)
typedef struct Node
{
int value, index;
}Node;
class Solution
{
public:
static bool cmp(const Node &a, const Node &b)
{
return a.value < b.value;
}
vector<int> twoSum(vector<int> &numbers, int target)
{
vector<int> ans;
vector<Node> nn;
int size = numbers.size();
int i, j;
for(i = 0; i < size; i++)
{
Node add;
add.value = numbers[i];
add.index = i;
nn.push_back(add);
}
sort(nn.begin(), nn.end(), cmp);
i = 0, j = size-1;
while(i < j)
{
if(nn[i].value+nn[j].value == target)
{
ans.push_back(nn[i].index+1);
ans.push_back(nn[j].index+1);
break;
}
else if(nn[i].value+nn[j].value > target)
j--;
else i++;
}
sort(ans.begin(), ans.end());
//cout << ans[0] << " " << ans[1] << endl;
return ans;
}
};
第六题:
Path Sum
地址:http://oj.leetcode.com/problems/path-sum/
分析:递归。。。
代码:
(C++版)
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int target;
class Solution
{
public:
static bool dfs(TreeNode *root, int count)
{
count += root->val;
if(count == target && root->left == NULL && root->right == NULL) return true;
if(root->left != NULL)
{
if(dfs(root->left, count) == true) return true;
}
if(root->right != NULL)
{
if(dfs(root->right, count) == true) return true;
}
return false;
}
bool hasPathSum(TreeNode *root, int sum)
{
bool flag = false;
target = sum;
if(root == NULL) return flag;
flag = dfs(root, 0);
return flag;
}
};
第七题:
Path Sum II
地址:http://oj.leetcode.com/problems/path-sum-ii/
分析:递归。
代码:
(C++版)
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int target;
vector<vector<int>> ans;
vector<int> add;
class Solution
{
public:
static void dfs(TreeNode *root, int count)
{
count += root->val;
add.push_back(root->val);
if(root->left == NULL && root->right == NULL)
{
if(count == target)
ans.push_back(add);
add.pop_back();
return ;
}
if(root->left != NULL)
{
dfs(root->left, count);
}
if(root->right != NULL)
dfs(root->right, count);
add.pop_back();
return ;
}
vector<vector<int> > pathSum(TreeNode *root, int sum)
{
target = sum;
if(root == NULL) return ans;
ans.clear();
add.clear();
dfs(root, 0);
return ans;
}
};
第八题:
Single Number II
地址:http://oj.leetcode.com/problems/single-number-ii/
分析:类似于前面那个single number,转化为3进制。注意正数与负数。
代码:
(C++版)
int arr[1000];
int ar[1000];
class Solution
{
public:
int singleNumber(int A[], int n)
{
int i, pos;
if(n == 1) return A[0];
for(i = 0;i < 1000; i++) arr[i] = ar[i] = 0;
for(i = 0; i < n; i++)
{
if(A[i] >= 0)
{
pos = 0;
long long int num = A[i];
while(num > 0)
{
arr[pos] += num%3;
arr[pos] %= 3;
num /= 3;
pos += 1;
}
}
else
{
pos = 0;
long long int num = (long long int)0-A[i];
while(num > 0)
{
ar[pos] += num%3;
ar[pos] %= 3;
num /= 3;
pos += 1;
}
}
}
for(i = 100;i >= 0; i--)
if(arr[i] != 0) break;
long long ans = 0;
for( ; i >= 0; i--)
{
ans *= 3;
ans += arr[i];
}
if(ans == 0)
{
for(i = 100; i >= 0; i--)
if(ar[i] != 0) break;
for(; i >= 0; i--)
{
ans *= 3;
ans += ar[i];
}
ans = 0 - ans;
}
return ans;
}
};
第九题:
Jump Game
地址:http://oj.leetcode.com/problems/jump-game/
分析:如上Jump Game II
代码:
(Python版)
class Solution:
# @param A, a list of integers
# @return an integer
def jump(self, A):
l1 = len(A)
right = A[0]
if l1 == 1:return 0
if right >= l1-1: return 1
if right == 0: ans = 0
else: ans = 1
maxnum = 0
i = 1
while i < l1:
if i <= right:
if i+A[i] > maxnum:
maxnum = i+A[i]
i += 1
else:
if maxnum == right:
if right >= l1-1:
return True
else:
return False
else: right = maxnum
return True
第十题:
Combination Sum II
地址:http://oj.leetcode.com/problems/combination-sum-ii/
分析:DFS
代码:
(C++版)
vector<vector<int>> ans;
vector<int> add;
int visit[1000];
class Solution
{
public:
vector<int> number;
int len;
static bool cmp(const vector<int> &a, const vector<int> &b)
{
int i;
if(a.size() != b.size()) return a.size() < b.size();
for(i = 0; i < a.size(); i++)
if(a[i] != b[i]) return a[i] < b[i];
return false;
}
void dfs(int sum, int pos, int target)
{
int i;
if(sum == target)
{
ans.push_back(add);
return;
}
for(i = pos; i < len; i++)
{
if(visit[i] == 0)
{
if(sum+number[i] <= target)
{
visit[i] = 1;
add.push_back(number[i]);
dfs(sum+number[i], i+1, target);
add.pop_back();
visit[i] = 0;
}
}
}
}
vector<vector<int> > combinationSum2(vector<int> &num, int target)
{
len = num.size();
sort(num.begin(), num.end());
int i, j;
number = num;
ans.clear();
add.clear();
for(i = 0; i < len; i++) visit[i] = 0;
dfs(0, 0, target);
vector<vector<int>> aaa;
sort(ans.begin(), ans.end(), cmp);
if(ans.size() == 0) return ans;
int k = 0;
aaa.push_back(ans[0]);
for(i = 1; i < ans.size(); i++)
{
if(ans[i].size() == aaa[k].size())
{
int idx;
for(idx = 0; idx < ans[i].size(); idx++)
{
if(ans[i][idx] != aaa[k][idx])break;
}
if(idx != ans[i].size())
{
aaa.push_back(ans[i]);
k++;
}
}
else
{
aaa.push_back(ans[i]);
k++;
}
}
return aaa;
}
};
第十一题:
Combination Sum
地址:oj.leetcode.com/problems/combination-sum/
分析:DFS,比Sum II 简单不少。
代码:
(C++版)
vector<vector<int>> ans;
vector<int> add;
int size;
vector<int> number;
class Solution
{
public:
static void dfs(int pos, int sum, int target)
{
int i;
if(sum == target)
{
ans.push_back(add);
return;
}
for(i = pos; i < size; i++)
{
if(sum+number[i] <= target)
{
add.push_back(number[i]);
dfs(i, sum+number[i], target);
add.pop_back();
}
}
}
vector<vector<int> > combinationSum(vector<int> &candidates, int target)
{
size = candidates.size();
sort(candidates.begin(), candidates.end());
number = candidates;
add.clear();
ans.clear();
dfs(0, 0, target);
return ans;
}
};
第十二题:
Remove Duplicates from Sorted Array
地址:http://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/
分析:水题。注意A为空时的处理。
代码:
(C++版)
class Solution
{
public:
int removeDuplicates(int A[], int n)
{
int i, j = 1;
int len = 1;
if(n == 0) return 0;
for(i = 1; i < n; i++)
if(A[i] != A[i-1])
A[j] = A[i], j++, len++;
return len;
}
};
第十三题
Remove Element
地址:http://oj.leetcode.com/problems/remove-element/
分析:水题
代码:
(C++版)
class Solution
{
public:
int removeElement(int A[], int n, int elem)
{
int i, j;
i = j = 0;
if(n == 0) return 0;
for(i = 0; i < n; i++)
{
if(A[i] == elem)
j++;
else
A[i-j] = A[i];
}
return n - j;
}
};
第十四题
Remove Duplicates from Sorted Array II
地址:http://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
分析:哎。。。
代码:
(C++版)
class Solution
{
public:
int removeDuplicates(int A[], int n)
{
int i, j = 1, k = 0;
for(i = 1; i < n; i++)
{
if(A[i] == A[i-1])
{
j++;
if (j > 2) k++;
}
else
j = 1;
A[i-k] = A[i];
}
return n-k;
}
};
第十五题:
Unique Paths
地址:http://oj.leetcode.com/problems/unique-paths/
分析:机器人只能往右走或者往下走。简单DP。公式 dp[i][j] = dp[i][j-1] + dp[i-1][j];
代码:
(C++版)
int dp[110][110];
class Solution
{
public:
int uniquePaths(int m, int n)
{
int i, j;
for (i = 0; i < 110; i++) for (j = 0; j < 110; j++) dp[i][j] = 0;
dp[0][1] = 1;
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++)
dp[i][j] = dp[i-1][j] + dp[i][j-1];
return dp[m][n];
}
};
第十六题:
Unique Paths II
地址:http://oj.leetcode.com/problems/unique-paths-ii/
分析:如上题。只不过在grid[i][j] = 1时,dp[i+1][j+1] = 0;
代码:
(C++版)
int dp[110][110];
class Solution
{
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid)
{
int m, n;
int i, j;
m = obstacleGrid.size();
if (m == 0) return 0;
n = obstacleGrid[0].size();
memset(dp, 0, sizeof(dp));
dp[0][1] = 1;
for (i = 1; i <= m; i++)
{
for(j = 1; j <= n; j++)
{
if (obstacleGrid[i-1][j-1] == 1) dp[i][j] = 0;
else dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m][n];
}
};
第十七题:
Binary Tree Preorder Traversal
地址:http://oj.leetcode.com/problems/binary-tree-preorder-traversal/
分析:PreOrder Travel
代码:
(C++版)
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
vector<int> ans;
class Solution
{
public:
static void dfs(TreeNode *root)
{
if (root == NULL) return ;
ans.push_back(root->val);
dfs(root->left);
dfs(root->right);
}
vector<int> preorderTraversal(TreeNode *root)
{
ans.clear();
dfs(root);
return ans;
}
};
第十八题:
Binary Tree Postorder Traversal
地址:http://oj.leetcode.com/problems/binary-tree-postorder-traversal/
分析:PostOrder
代码:
(C++版)
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
vector<int> ans;
class Solution
{
public:
static void dfs(TreeNode *root)
{
if (root == NULL) return;
dfs(root->left);
dfs(root->right);
ans.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode *root)
{
ans.clear();
dfs(root);
return ans;
}
};
第十九题
Surrounded Regions
地址:http://oj.leetcode.com/problems/surrounded-regions/
分析:反向思考,只BFS周边的'O
代码:
(C++版)
'
struct Point_
{
int x, y;
Point_(int a,int b):x(a), y(b){}
};
class Solution
{
public:
void solve(vector<vector<char>> &board)
{
int size1, size2;
int i, j;
size1 = board.size();
if (size1 == 0) return ;
size2 = board[0].size();
vector<Point_> vec;
for (i = 0; i < size1; i++)
{
for (j = 0; j < size2; j++)
{
if (board[i][j] == 'O' && (i == 0 || i == size1-1 || j == 0 || j == size2-1))
{
board[i][j] = 'D';
vec.push_back(Point_(i,j));
}
}
}
const int dir[4][2] = {1,0,-1,0,0,1,0,-1};
while (!vec.empty())
{
Point_ p = vec.back();
vec.pop_back();
for (i = 0; i < 4; i++)
{
int xx = p.x+dir[i][0];
int yy = p.y+dir[i][1];
if (xx < 0 || xx >= size1 || yy < 0 || yy >= size2 || board[xx][yy] != 'O') continue;
vec.push_back(Point_(xx, yy));
board[xx][yy] = 'D';
}
}
for (i = 0; i < size1; i++)
for (j = 0; j < size2; j++)
board[i][j] = board[i][j] == 'D' ? 'O' : 'X';
#if(0)
for (i = 0; i < size1; i++)
{
for (j = 0; j < size2; j++)
putchar(board[i][j]);
puts("");
}
#endif
}
};
第二十题
Word Search
地址:http://oj.leetcode.com/problems/word-search/
分析:DFS,不过感觉OJ有点坑。
代码:
(C++版)
int visit[110][110];
string target;
int col, row;
int len;
const int dir[4][2] = {1,0,-1,0,0,1,0,-1};
int dfs(vector<vector<char> > &board, int x,int y, int k)
{
int i;
if (board[x][y] != target[k-1]) return 0;
if (k == len) return 1;
visit[x][y] = 1;
for (i = 0; i < 4; i++)
{
int xx = x + dir[i][0];
int yy = y + dir[i][1];
if (xx < 0 || xx >= col) continue;
if (yy < 0 || yy >= row) continue;
if (visit[xx][yy]) continue;
if (dfs(board, xx, yy, k+1)) return 1;
}
visit[x][y] = 0;
return 0;
}
class Solution
{
public:
bool exist(vector<vector<char> > &board, string word)
{
int i, j;
len = word.length();
if (word == "") return false;
col = board.size();
if (col == 0) return false;
row = board[0].size();
target = word;
memset(visit, 0, sizeof(visit));
for (i = 0; i < col; i++)
{
for (j = 0; j < row; j++)
{
if (dfs(board, i, j, 1)) return true;
}
}
return false;
}
};