Jump Game
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
从后向前,不断迭代最后一个能跳到末尾的index
bool canJump(vector<int>& nums) {
int zeroNum = 0;
int lastJump = nums.size() - 1;
for(int i = nums.size() - 2; i > -1; i--){
if(i + nums[i] >= lastJump)
lastJump = i;
}
return lastJump == 0;
}
Missing Number
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3]
return 2
.
解法1:向量加和做减
int missingNumber(vector<int>& nums) {
int n = nums.size();
int sum = n * (n + 1) / 2;
int vecsum = 0;
for(int i = 0; i < nums.size(); i++){
vecsum += nums[i];
}
return sum - vecsum;
}
解法2:bit manipulation
The basic idea is to use XOR operation. We all know that a^b^b =a, which means two xor operations with the same number will eliminate the number and reveal the original number.
int missingNumber(vector<int>& nums) {
int result = nums.size();
int i=0;
for(int num:nums){
result ^= num;
result ^= i;
i++;
}
return result;
}
Combination Sum
回溯。
开始写的时候两个地方出现了问题。一是,初始化了太多vector,造成了很多开销;二是采用了未排序在寻找可能组合时遍历整个子序列的方式。在排序之后,无论是从后往前还是从前往后,是可以剪掉一部分遍历操作的。就算测试用例序列很不友好,排序的时间很久,应该还是排序后快一些吧。
class Solution {
public:
std::vector<std::vector<int> > combinationSum(std::vector<int> &candidates, int target) {
std::sort(candidates.begin(), candidates.end());
std::vector<std::vector<int> > res;
std::vector<int> combination;
combinationSum(candidates, target, res, combination, 0);
return res;
}
private:
void combinationSum(std::vector<int> &candidates, int target, std::vector<std::vector<int> > &res, std::vector<int> &combination, int begin) {
if (!target) {
res.push_back(combination);
return;
}
for (int i = begin; i != candidates.size() && target >= candidates[i]; ++i) { //这个地方剪掉了一部分遍历
combination.push_back(candidates[i]);
combinationSum(candidates, target - candidates[i], res, combination, i);
combination.pop_back();
}
}
};