[LeetCode] 1.两数之和

这道题好像没用成功回溯法。。。。反而变难了

class Solution {
    public int[] twoSum(int[] nums, int target) {
        List<Integer> list;
        return sum(nums,target,0,list,0);
    }

    public int[] sum(int[] nums, int target,int sum,List<Integer> list,int index){
        if(index==nums.length){
            if(sum=target){
                return new ArrayList<>(list);
            }else{
                return list;
            }
        }
        
        for(int i=index;i<nums.length;i++){
            sum +=nums[i];
            sum(nums,target,sum,list,index+1);。。。。。。。。。没写完
            sum -=nums[i];
        }
    }
}

方法二:官方的

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[] { map.get(complement), i };
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}
原文地址:https://www.cnblogs.com/doyi111/p/12630104.html