日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

加/减数组中的值得到指定的和 Target Sum

發布時間:2025/7/14 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 加/减数组中的值得到指定的和 Target Sum 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

為什么80%的碼農都做不了架構師?>>> ??

問題:

You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols?+?and?-. For each integer, you should choose one from?+?and?-?as its new symbol.

Find out how many ways to assign symbols to make sum of integers equal to target S.

Example 1:

Input: nums is [1, 1, 1, 1, 1], S is 3. Output: 5 Explanation: -1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3 There are 5 ways to assign symbols to make the sum of nums be target 3.

Note:

  • The length of the given array is positive and will not exceed 20.
  • The sum of elements in the given array will not exceed 1000.
  • Your output answer is guaranteed to be fitted in a 32-bit integer.
  • 解決:

    ① ?dfs。時間復雜度O(2^n)。

    class Solution { //706ms
    ? ? int count = 0;
    ? ? public int findTargetSumWays(int[] nums, int S) {
    ? ? ? ? if (nums == null || nums.length == 0) return 0;
    ? ? ? ? dfs(nums,S,0,0);
    ? ? ? ? return count;
    ? ? }
    ? ? public void dfs(int[] nums,int s,int i,int sum){
    ? ? ? ? if (i == nums.length){
    ? ? ? ? ? ? if (s == sum){
    ? ? ? ? ? ? ? ? count ++;
    ? ? ? ? ? ? }
    ? ? ? ? ? ? return;
    ? ? ? ? }
    ? ? ? ? dfs(nums,s,i + 1,sum + nums[i]);
    ? ? ? ? dfs(nums,s,i + 1,sum - nums[i]);
    ? ? }
    }

    ②?遞歸解決方案非常慢,因為它的運行時間是指數的。

    原問題等價于:找到一個正數的子集,其余為負數,其總和為target。

    設P為正數子集,N為負數子集。例如:

    給定nums = [1,2,3,4,5]和target = 3,那么一個可能的解決方案是+ 1 - 2 + 3 - 4 + 5 = 3。

    此時正子集是P = [1,3,5],負子集是N = [2,4]。

    下面將其轉換為子集總和問題:

    sum(P) - sum(N) = target sum(P) + sum(N) + sum(P) - sum(N) = target + sum(P) + sum(N)2 * sum(P) = target + sum(nums)

    所以原來的問題已被轉換為子集和問題如下:
    找出nums的一個子集P,使得sum(P)=(target + sum(nums))/ 2?

    class Solution { //17ms
    ? ? public int findTargetSumWays(int[] nums, int S) {
    ? ? ? ? int sum = 0;
    ? ? ? ? for (int i = 0;i < nums.length;i ++){
    ? ? ? ? ? ? sum += nums[i];
    ? ? ? ? }
    ? ? ? ? if (S > sum || (sum + S) % 2 == 1) return 0;//只有該式為偶數時才有符合條件的解
    ? ? ? ? return subsetSum(nums,(sum + S) / 2);
    ? ? }
    ? ? public int subsetSum(int[] nums,int S){
    ? ? ? ? int[] dp = new int[S + 1];
    ? ? ? ? dp[0] = 1;//初始記錄0的位置為1
    ? ? ? ? for (int i = 0;i < nums.length;i ++){
    ? ? ? ? ? ? for (int j = S;j >= nums[i];j --){
    ? ? ? ? ? ? ? ? dp[j] += dp[j - nums[i]];
    ? ? ? ? ? ? }
    ? ? ? ? }
    ? ? ? ? return dp[S];
    ? ? }
    }

    轉載于:https://my.oschina.net/liyurong/blog/1603737

    總結

    以上是生活随笔為你收集整理的加/减数组中的值得到指定的和 Target Sum的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。