日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2025/7/14 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 加/减数组中的值得到指定的和 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的全部內容,希望文章能夠幫你解決所遇到的問題。

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