亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

迭代數字數組的每個排列

迭代數字數組的每個排列

江戶川亂折騰 2024-01-17 16:38:22
我的問題是這樣的:我在一個數組中有 n 個數字,每個數字都有一個最大值 m,我想通過單獨遞增它們直到達到最大值來迭代這些數字的每個排列。一個例子:[0,0,0,0]Integer @ index 0 has a max value of 5Integer @ index 1 has a max value of 3Integer @ index 2 has a max value of 4Integer @ index 3 has a max value of 6Output: [0,0,0,1][0,0,0,2][0,0,0,3]...[0,1,1,0][0,1,1,1][0,1,1,2][0,1,1,3]...[5,0,2,1][5,0,2,2]etc.Python有帶有product函數的itertools,這可以解決我的問題,但看起來Java沒有類似的東西。遞歸似乎是可行的方法,但我可以找出前進的方向。有誰知道如何實現上述輸出?提前致謝 :-)
查看完整描述

1 回答

?
MYYA

TA貢獻1868條經驗 獲得超4個贊

從技術上講,排列意味著某些元素的重新排序,例如,[3,1,2]是 的排列[1,2,3]。您所要求的相當于迭代笛卡爾積,因此 Python 函數被命名為product


正如您正確地注意到的,遞歸是這里的方法。這是因為生成 的所有序列[5,3,4,6]需要生成[3,4,6]以 0 開頭的所有序列,然后再次以 1 開頭,依此類推,直到 5。

import java.util.Arrays;


public class CartesianProduct {

? ? public static void main(String[] args) {

? ? ? ? printAll(5, 3, 4, 6);

? ? }


? ? public static void printAll(int... maxes) {

? ? ? ? int[] current = new int[maxes.length];

? ? ? ? printAll(maxes, current, 0);

? ? }


? ? private static void printAll(int[] maxes, int[] current, int i) {

? ? ? ? if(i == current.length) {

? ? ? ? ? ? System.out.println(Arrays.toString(current));

? ? ? ? } else {

? ? ? ? ? ? int max = maxes[i];

? ? ? ? ? ? for(int j = 0; j <= max; ++j) {

? ? ? ? ? ? ? ? current[i] = j;

? ? ? ? ? ? ? ? printAll(maxes, current, i+1);

? ? ? ? ? ? }

? ? ? ? }

? ? }

}

變量i是我們當前選擇值的位置的索引,變量j是該位置的當前值,數組current保存當前序列。遞歸的基本情況是在所有位置都選擇了值,然后我們打印。


查看完整回答
反對 回復 2024-01-17
  • 1 回答
  • 0 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號