mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-09 23:40:05 +08:00
Retranslate the complete Japanese online edition from Chinese (#2008)
* Retranslate the complete Japanese online edition from Chinese * Fit Japanese homepage labels and localize heading permalinks * Point Japanese contribution instructions to the Japanese preview * Replace locale conditionals with multilingual UI tables
This commit is contained in:
@@ -9,35 +9,35 @@ package chapter_backtracking;
|
||||
import java.util.*;
|
||||
|
||||
public class subset_sum_i {
|
||||
/* バックトラッキング:部分和 I */
|
||||
/* バックトラッキング:部分集合和 I */
|
||||
static void backtrack(List<Integer> state, int target, int[] choices, int start, List<List<Integer>> res) {
|
||||
// 部分集合の和が target に等しければ、解を記録
|
||||
// 部分集合の和が target と等しくなったら、解を記録する
|
||||
if (target == 0) {
|
||||
res.add(new ArrayList<>(state));
|
||||
return;
|
||||
}
|
||||
// すべての選択肢を走査
|
||||
// 枝刈り 2: start から走査し、重複する部分集合の生成を避ける
|
||||
// すべての選択肢を走査する
|
||||
// 枝刈り 2:start から走査を始め、重複した部分集合の生成を避ける
|
||||
for (int i = start; i < choices.length; i++) {
|
||||
// 枝刈り1:部分集合の和が target を超えたら、直ちにループを終了する
|
||||
// 配列はソート済みで後続要素のほうが大きく、部分集合の和は必ず target を超えるため
|
||||
// 枝刈り 1:部分集合の和が target を超えたら、直ちにループを終了する
|
||||
// 配列はソート済みで後ろの要素ほど大きいため、部分集合の和が必ず target を超えるからである
|
||||
if (target - choices[i] < 0) {
|
||||
break;
|
||||
}
|
||||
// 試す:選択を行い、target と start を更新
|
||||
// 試行:選択を行い、target, start を更新する
|
||||
state.add(choices[i]);
|
||||
// 次の選択へ進む
|
||||
// 次の選択に進む
|
||||
backtrack(state, target - choices[i], choices, i, res);
|
||||
// バックトラック:選択を取り消し、前の状態に戻す
|
||||
// 復元:選択を取り消し、以前の状態に戻す
|
||||
state.remove(state.size() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* 部分和 I を解く */
|
||||
/* 部分集合和 I を解く */
|
||||
static List<List<Integer>> subsetSumI(int[] nums, int target) {
|
||||
List<Integer> state = new ArrayList<>(); // 状態(部分集合)
|
||||
Arrays.sort(nums); // nums をソート
|
||||
int start = 0; // 開始点を走査
|
||||
Arrays.sort(nums); // nums をソートする
|
||||
int start = 0; // 走査の開始位置
|
||||
List<List<Integer>> res = new ArrayList<>(); // 結果リスト(部分集合のリスト)
|
||||
backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
@@ -50,6 +50,6 @@ public class subset_sum_i {
|
||||
List<List<Integer>> res = subsetSumI(nums, target);
|
||||
|
||||
System.out.println("入力配列 nums = " + Arrays.toString(nums) + ", target = " + target);
|
||||
System.out.println("和が " + target + " に等しいすべての部分集合 res = " + res);
|
||||
System.out.println("和が " + target + " になるすべての部分集合 res = " + res);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user