Array(7) -- Jump Game,Missing Number,Combination Sum

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();
        }
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值